<?php
// delete_transaction.php

require 'auth_check.php';
require_once 'db.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
if (!$id) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid id']);
    exit;
}

// Fetch upload path before deleting so we can clean up files
$stmt = $pdo->prepare("SELECT invoice_path FROM transactions WHERE id = ?");
$stmt->execute([$id]);
$row = $stmt->fetch();

if (!$row) {
    http_response_code(404);
    echo json_encode(['error' => 'Transaction not found']);
    exit;
}

// Delete the database record
$pdo->prepare("DELETE FROM transactions WHERE id = ?")->execute([$id]);

// Remove associated upload folder if it exists
$dir = __DIR__ . "/uploads/transactions/transaction_{$id}";
if (is_dir($dir)) {
    // Simple recursive delete
    $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
    foreach ($files as $file) {
        $file->isDir() ? rmdir($file->getRealPath()) : unlink($file->getRealPath());
    }
    rmdir($dir);
}

echo json_encode(['success' => true]);
