<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/bootstrap.php';
requireLogin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') { header('Location: beneficiary_documents.php'); exit; }
orphan_verify_csrf();

$id = (int)($_POST['id'] ?? 0);
if ($id <= 0) { header('Location: beneficiary_documents.php'); exit; }

$st = $pdo->prepare("SELECT * FROM beneficiary_documents WHERE id=?");
$st->execute([$id]);
$doc = $st->fetch(PDO::FETCH_ASSOC);
if (!$doc) { header('Location: beneficiary_documents.php'); exit; }

/**
 * Resolve a stored relative path (like "zaka_storage/...") to an absolute path under documents/
 * and delete it safely.
 */
function safeUnlinkInDocuments(?string $rel): bool
{
    $rel = trim((string)$rel);
    if ($rel === '') return false;

    $documentsRoot = realpath(dirname(__DIR__)); // .../documents
    if (!$documentsRoot) return false;

    // build absolute path inside documents
    $abs = $documentsRoot . DIRECTORY_SEPARATOR . ltrim(str_replace('\\', '/', $rel), '/');
    $real = realpath($abs);

    if ($real && is_file($real) && strpos($real, $documentsRoot) === 0) {
        @unlink($real);
        return !is_file($real);
    }
    return false;
}

/**
 * Delete any derived duplicates in beneficiary folder that share same prefix.
 * Example: if main is ".../151_id_card_front_486abc.jpg"
 * prefix becomes "151_id_card_front_486abc"
 * then delete files matching "151_id_card_front_486abc*"
 */
function cleanupDerivedFiles(int $beneficiaryId, array $paths): int
{
    $deleted = 0;

    $documentsRoot = realpath(dirname(__DIR__));
    if (!$documentsRoot) return 0;

    $baseDir = $documentsRoot . '/zaka_storage/beneficiaries_docs/' . $beneficiaryId;
    $baseReal = realpath($baseDir);
    if (!$baseReal || !is_dir($baseReal) || strpos($baseReal, $documentsRoot) !== 0) {
        return 0;
    }

    // collect prefixes from provided paths
    $prefixes = [];
    foreach ($paths as $rel) {
        $rel = trim((string)$rel);
        if ($rel === '') continue;
        $bn = basename(str_replace('\\', '/', $rel));
        if ($bn === '' || $bn === '.' || $bn === '..') continue;

        $dot = strrpos($bn, '.');
        $prefix = ($dot !== false) ? substr($bn, 0, $dot) : $bn;
        if ($prefix !== '') $prefixes[$prefix] = true;
    }

    if (!$prefixes) return 0;

    // scan dir and delete anything starting with any prefix
    $files = @scandir($baseReal);
    if (!is_array($files)) return 0;

    foreach ($files as $f) {
        if ($f === '.' || $f === '..') continue;
        $full = $baseReal . DIRECTORY_SEPARATOR . $f;
        if (!is_file($full)) continue;

        foreach ($prefixes as $p => $_) {
            if (str_starts_with($f, $p)) {
                @unlink($full);
                if (!is_file($full)) $deleted++;
                break;
            }
        }
    }

    // optional: remove empty folder
    $filesAfter = @scandir($baseReal);
    if (is_array($filesAfter)) {
        $left = array_values(array_filter($filesAfter, fn($x) => $x !== '.' && $x !== '..'));
        if (count($left) === 0) {
            @rmdir($baseReal);
        }
    }

    return $deleted;
}

$beneficiaryId = (int)($doc['beneficiary_id'] ?? 0);
$storedPath = (string)($doc['stored_path'] ?? '');
$thumbPath  = (string)($doc['thumb_path'] ?? '');

$deletedMain  = safeUnlinkInDocuments($storedPath);
$deletedThumb = safeUnlinkInDocuments($thumbPath);

// delete any extra generated duplicates (same prefix) داخل مجلد المستفيد
$deletedDerived = 0;
if ($beneficiaryId > 0) {
    $deletedDerived = cleanupDerivedFiles($beneficiaryId, [$storedPath, $thumbPath]);
}

// delete DB record
$pdo->prepare("DELETE FROM beneficiary_documents WHERE id=?")->execute([$id]);

if (function_exists('flashSuccess') && function_exists('flashError')) {
    if ($deletedMain || $deletedThumb || $deletedDerived > 0) {
        flashSuccess('تم حذف الوثيقة من قاعدة البيانات ومن السيرفر (مع تنظيف النسخ المكررة).');
    } else {
        flashError('تم حذف الوثيقة من قاعدة البيانات، لكن لم يتم العثور على الملف للحذف على السيرفر. تحقق من stored_path/thumb_path والصلاحيات.');
    }
}

header('Location: beneficiary_documents.php?beneficiary_id=' . (int)$beneficiaryId);
exit;