<?php

declare(strict_types=1);

require_once __DIR__ . '/../../includes/bootstrap.php';

$config = require __DIR__ . '/../../config/config.php';

auth_start_session();
auth_require_role(['admin']);

$reportId = (int)($_POST['report_id'] ?? 0);
$customerId = (int)($_POST['customer_id'] ?? 0);
$type = (string)($_POST['type'] ?? CustomerReportsService::TYPE_IPM_MAP);

if ($reportId <= 0 || $customerId <= 0) {
    header('Location: /pest/public/admin/customers.php');
    exit;
}

try {
    $pdo = Database::pdo();
    CustomerReportsService::ensureTable($pdo);

    $stmt = $pdo->prepare('SELECT report_id, customer_id, report_type, file_path FROM customer_reports WHERE report_id = :id LIMIT 1');
    $stmt->execute(['id' => $reportId]);
    $row = $stmt->fetch();

    if ($row && (int)$row['customer_id'] === $customerId) {
        $stored = (string)($row['file_path'] ?? '');

        $deleteCandidates = [];
        if (str_starts_with($stored, Constants::ASSET_ROOT . '/')) {
            $rel = substr($stored, strlen(Constants::ASSET_ROOT));
            $base = realpath(__DIR__ . '/../../assets') ?: (__DIR__ . '/../../assets');
            $deleteCandidates[] = rtrim($base, '/\\') . $rel;
        } elseif (str_starts_with($stored, Constants::APP_ROOT . '/')) {
            $rel = substr($stored, strlen(Constants::APP_ROOT));
            $base = realpath(__DIR__ . '/../') ?: (__DIR__ . '/../');
            $deleteCandidates[] = rtrim($base, '/\\') . $rel;
        } elseif (str_starts_with($stored, '/uploads/')) {
            $assetBase = realpath(__DIR__ . '/../../assets') ?: (__DIR__ . '/../../assets');
            $publicBase = realpath(__DIR__ . '/../') ?: (__DIR__ . '/../');
            $deleteCandidates[] = rtrim($assetBase, '/\\') . $stored;
            $deleteCandidates[] = rtrim($publicBase, '/\\') . $stored;
        }

        $stmtDel = $pdo->prepare('DELETE FROM customer_reports WHERE report_id = :id');
        $stmtDel->execute(['id' => $reportId]);

        foreach ($deleteCandidates as $abs) {
            $real = realpath($abs);
            if ($real === false) {
                continue;
            }

            $assetsRoot = realpath(__DIR__ . '/../../assets') ?: (__DIR__ . '/../../assets');
            $publicRoot = realpath(__DIR__ . '/../') ?: (__DIR__ . '/../');

            $assetsRoot = rtrim(str_replace('\\', '/', $assetsRoot), '/');
            $publicRoot = rtrim(str_replace('\\', '/', $publicRoot), '/');
            $realNorm = str_replace('\\', '/', $real);

            $isInsideAssets = str_starts_with($realNorm, $assetsRoot . '/uploads/');
            $isInsidePublic = str_starts_with($realNorm, $publicRoot . '/uploads/');

            if ($isInsideAssets || $isInsidePublic) {
                @unlink($real);
            }
        }
    }
} catch (Throwable $e) {
    // ignore
}

header('Location: /pest/public/admin/customer_reports_view.php?customer_id=' . $customerId . '&type=' . urlencode($type));
exit;
