<?php
// case_file_delete.php (SAFE DELETE) - delete case file (DB + physical file) with branch/role permission
declare(strict_types=1);
session_start();

if (empty($_SESSION['user_id'])) {
  header("Location: index.html?e=1");
  exit;
}

require_once __DIR__ . '/db.php';

/* ===== Get PDO (supports db() or $pdo) ===== */
$pdo = null;
if (function_exists('db')) {
  $pdo = db();
} elseif (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
  $pdo = $GLOBALS['pdo'];
}
if (!$pdo instanceof PDO) {
  http_response_code(500);
  exit('DB not ready');
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

function redirect_back(int $caseId, string $msg = '', string $err = ''): void {
  $url = 'case_files.php?case_id=' . $caseId;
  if ($msg !== '') $url .= '&msg=' . urlencode($msg);
  if ($err !== '') $url .= '&err=' . urlencode($err);
  header('Location: ' . $url);
  exit;
}

/* ===== Only POST ===== */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  http_response_code(405);
  exit('Method not allowed');
}

$fileId = (int)($_POST['file_id'] ?? 0);
$caseId = (int)($_POST['case_id'] ?? 0);
if ($fileId <= 0 || $caseId <= 0) {
  http_response_code(400);
  exit('Missing file_id/case_id');
}

$role = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
$isAdmin = in_array($role, ['OWNER', 'ADMIN'], true);
$sessionBranchId = (int)($_SESSION['branch_id'] ?? 1);

try {
  // 1) Get file + case branch (for permission)
  $st = $pdo->prepare("
    SELECT cf.id, cf.case_id, cf.file_path, cf.file_name, c.branch_id
    FROM case_files cf
    JOIN cases c ON c.id = cf.case_id
    WHERE cf.id = ? AND cf.case_id = ?
    LIMIT 1
  ");
  $st->execute([$fileId, $caseId]);
  $row = $st->fetch();

  if (!$row) {
    redirect_back($caseId, '', 'الملف غير موجود.');
  }

  $caseBranchId = (int)($row['branch_id'] ?? 0);

  // 2) Permission:
  //    - ADMIN/OWNER: allowed
  //    - STAFF: allowed only if same branch
  if (!$isAdmin && $caseBranchId !== $sessionBranchId) {
    redirect_back($caseId, '', 'غير مصرح بحذف هذا الملف.');
  }

  $filePathDb = (string)($row['file_path'] ?? '');
  $fileName   = (string)($row['file_name'] ?? '');

  // 3) Delete DB row (first) or file (first)? safer: delete DB after file success,
  //    but we will try both and not fail hard if file missing.
  $pdo->beginTransaction();

  $del = $pdo->prepare("DELETE FROM case_files WHERE id=? AND case_id=? LIMIT 1");
  $del->execute([$fileId, $caseId]);

  $pdo->commit();

  // 4) Delete physical file if exists and inside project directory
  // Normalize path
  $filePathDb = str_replace('\\', '/', trim($filePathDb));

  if ($filePathDb !== '') {
    // If stored as absolute path, keep it; if relative, make it relative to project root
    $candidate = $filePathDb;

    if (!preg_match('~^/|^[A-Za-z]:/~', $candidate)) {
      // relative path: from project root
      $candidate = __DIR__ . '/' . ltrim($candidate, '/');
    }

    $real = realpath($candidate);
    $root = realpath(__DIR__);

    // Security: only delete if inside this project folder
    if ($real && $root && strpos($real, $root) === 0 && is_file($real)) {
      @unlink($real);
    }
  }

  redirect_back($caseId, 'تم حذف الملف بنجاح: ' . $fileName);

} catch (Throwable $e) {
  if ($pdo->inTransaction()) $pdo->rollBack();
  redirect_back($caseId, '', 'حدث خطأ أثناء الحذف.');
}