<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
header('Content-Type: application/json');

// সিকিউরিটি: লগইন না থাকলে ডিলিট করতে পারবে না
if (!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit();
}

// Config লোড করা
$doc_root = rtrim($_SERVER['DOCUMENT_ROOT'], '/');
require_once $doc_root . '/config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
    $invoice_id = intval($_POST['id']);
    $user_id = $_SESSION['user_id'];

    // ডিলিট করার কুয়েরি (শুধুমাত্র নিজের তৈরি করা ইনভয়েস ডিলিট হবে, অন্য কারোটা নয়)
    $stmt = $conn->prepare("DELETE FROM user_invoices WHERE id = ? AND user_id = ?");
    $stmt->bind_param("ii", $invoice_id, $user_id);
    
    if ($stmt->execute()) {
        if ($stmt->affected_rows > 0) {
            echo json_encode(['status' => 'success', 'message' => 'Invoice deleted successfully']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Invoice not found or already deleted']);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Failed to delete from database']);
    }
    
    $stmt->close();
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
}
?>