<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_file_id'])) {
    $file_id = (int)($_POST['delete_file_id'] ?? 0);

    if ($file_id > 0 && isset($db)) {
        try {
            $hasCompanyWorkspace = isset($_SESSION['active_company_id']) && $_SESSION['active_company_id'] !== '';
            $active_company_id = $hasCompanyWorkspace ? (int) $_SESSION['active_company_id'] : null;
            $user_id = (int) ($_SESSION['user_id'] ?? 0);

            if ($hasCompanyWorkspace) {
                $stmt = $db->prepare("
                    SELECT file_path
                    FROM documents
                    WHERE id = :id
                      AND company_id = :company_id
                ");
                $stmt->execute([
                    ':id' => $file_id,
                    ':company_id' => $active_company_id
                ]);
            } else {
                $stmt = $db->prepare("
                    SELECT file_path
                    FROM documents
                    WHERE id = :id
                      AND user_id = :user_id
                ");
                $stmt->execute([
                    ':id' => $file_id,
                    ':user_id' => $user_id
                ]);
            }

            $file = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($file) {
                $absolutePath = __DIR__ . '/' . ltrim($file['file_path'], '/');

                if (!empty($file['file_path']) && file_exists($absolutePath)) {
                    @unlink($absolutePath);
                }

                $stmt = $db->prepare("DELETE FROM documents WHERE id = :id");
                $stmt->execute([':id' => $file_id]);
            }

        } catch (PDOException $e) {
            // optional: log error
        }

        // reload page
        header("Location: " . $_SERVER['REQUEST_URI']);
        exit;
    }
}