<?php
require_once('../../config.php');
if($_SERVER['REQUEST_METHOD']!=='POST')exit;
$csrf=$_POST['csrf']??'';
if($csrf===''||!hash_equals($_SESSION['csrf'],$csrf)){$prev=$_SERVER['HTTP_REFERER']??'index.php';header("Location:$prev");exit;}
if(!isset($_SESSION['user'])||!has_permission('outboxdelete')){header("Location:".($applicationBaseDir??'/')."login.php");exit;}
$faxname=basename(trim($_POST['fax']??''));
$dirname=basename(trim($_POST['dir']??''));
if($faxname===''){header("Location:".($applicationBaseDir??'/')."fax_outbox.php?dir=".urlencode($dirname));exit;}
$baseArchivePath=realpath(rtrim($applicationOutboxPath,'/'));
$targetDir=realpath($baseArchivePath.($dirname!==''?DIRECTORY_SEPARATOR.$dirname:''));
if(!$baseArchivePath||!$targetDir||!is_dir($targetDir)||($targetDir!==$baseArchivePath&&strpos($targetDir,$baseArchivePath.DIRECTORY_SEPARATOR)!==0)){
header("Location:".($applicationBaseDir??'/')."fax_outbox.php");
exit;
}
clearstatcache();
$baseFileName=pathinfo($faxname,PATHINFO_FILENAME);
$extensions=[
'.pdf'=>['application/pdf'],
'.tiff'=>['image/tiff','image/tif','image/x-tiff'],
'.meta'=>['application/json','text/plain'],
];
$deletedCount=0;
foreach($extensions as $ext=>$allowedMimes){
$filePath=$targetDir.DIRECTORY_SEPARATOR.$baseFileName.$ext;
$realFilePath=realpath($filePath);
if($realFilePath&&is_file($realFilePath)&&strpos($realFilePath,$targetDir.DIRECTORY_SEPARATOR)===0&&!is_link($realFilePath)){
$finfo=finfo_open(FILEINFO_MIME_TYPE);
$mime=finfo_file($finfo,$realFilePath);
finfo_close($finfo);
if(in_array($mime,$allowedMimes,true)){if(@unlink($realFilePath))$deletedCount++;}
}}
if($deletedCount>0){header("Location:".($applicationBaseDir??'/')."fax_outbox.php?dir=".urlencode($dirname));
}else{$fallback=($applicationBaseDir??'/')."fax_outbox.php?dir=".urlencode($dirname);header("Location:".($_SERVER['HTTP_REFERER']??$fallback));}
exit;
