<?php
// upload_case_file.php (SAVE INTO public_html/HLG-Justice-Hub/uploads/cases)
declare(strict_types=1);
session_start();
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/db.php';

if (empty($_SESSION['user_id'])) {
  http_response_code(401);
  echo json_encode(['success'=>false,'error'=>'UNAUTHORIZED']);
  exit;
}

$pdo = function_exists('db') ? db() : null;
if (!$pdo instanceof PDO) {
  http_response_code(500);
  echo json_encode(['success'=>false,'error'=>'DB_NOT_READY']);
  exit;
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$caseId   = (int)($_POST['case_id'] ?? 0);
$branchId = (int)($_POST['branch_id'] ?? ($_SESSION['branch_id'] ?? 0));
if ($caseId <= 0) {
  http_response_code(400);
  echo json_encode(['success'=>false,'error'=>'CASE_ID_MISSING']);
  exit;
}

if (empty($_FILES['file']) || !is_uploaded_file($_FILES['file']['tmp_name'])) {
  http_response_code(400);
  echo json_encode(['success'=>false,'error'=>'FILE_MISSING']);
  exit;
}

$f = $_FILES['file'];
if (($f['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
  http_response_code(400);
  echo json_encode(['success'=>false,'error'=>'UPLOAD_ERROR','code'=>$f['error']]);
  exit;
}

/* حد 10MB */
$max = 10 * 1024 * 1024;
if ((int)$f['size'] > $max) {
  http_response_code(400);
  echo json_encode(['success'=>false,'error'=>'FILE_TOO_LARGE']);
  exit;
}

/* امتدادات مسموحة */
$allowedExt = ['pdf','png','jpg','jpeg','doc','docx','xls','xlsx'];
$origName = (string)($f['name'] ?? 'file');
$origName = preg_replace('/[^\pL\pN\.\-\_\s]+/u', '', $origName);
$ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
if ($ext === '' || !in_array($ext, $allowedExt, true)) {
  http_response_code(400);
  echo json_encode(['success'=>false,'error'=>'EXT_NOT_ALLOWED']);
  exit;
}

/* مسار الحفظ الفعلي داخل HLG-Justice-Hub */
$caseDirDisk = __DIR__ . "/uploads/cases/{$caseId}";
if (!is_dir($caseDirDisk)) {
  if (!mkdir($caseDirDisk, 0775, true)) {
    http_response_code(500);
    echo json_encode(['success'=>false,'error'=>'MKDIR_FAILED','dir'=>$caseDirDisk]);
    exit;
  }
}
if (!is_writable($caseDirDisk)) {
  http_response_code(500);
  echo json_encode(['success'=>false,'error'=>'DIR_NOT_WRITABLE','dir'=>$caseDirDisk]);
  exit;
}

/* اسم آمن للملف */
$stamp = date('Ymd_His');
$rand  = bin2hex(random_bytes(4));
$safeBase = pathinfo($origName, PATHINFO_FILENAME);
$safeBase = trim(preg_replace('/\s+/', '_', $safeBase));
if ($safeBase === '') $safeBase = 'file';

$newName = $safeBase . '_' . $stamp . '_' . $rand . '.' . $ext;
$targetDisk = $caseDirDisk . '/' . $newName;

/* نقل الملف */
if (!move_uploaded_file($f['tmp_name'], $targetDisk)) {
  http_response_code(500);
  echo json_encode(['success'=>false,'error'=>'MOVE_FAILED']);
  exit;
}

/* MIME */
$mime = '';
if (function_exists('mime_content_type')) {
  $mime = (string)@mime_content_type($targetDisk);
}
if ($mime === '') $mime = 'application/octet-stream';

/* مسار ويب نسبي (مهم جداً) */
$relativeWebPath = "uploads/cases/{$caseId}/{$newName}";

/* خزّن في قاعدة البيانات */
$st = $pdo->prepare("
  INSERT INTO case_files (case_id, file_name, file_path, file_type, file_size, created_at)
  VALUES (?, ?, ?, ?, ?, NOW())
");
$st->execute([
  $caseId,
  $origName,          // الاسم الظاهر
  $relativeWebPath,   // هذا اللي يمنع 404
  $mime,
  (int)$f['size'],
]);

echo json_encode(['success'=>true,'path'=>$relativeWebPath,'id'=>$pdo->lastInsertId()]);