<?php
session_start();
include '../layouts/dbconn.php';
include '../layouts/session.php';

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

// Auth check
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorised']);
    exit();
}

// Role check — only these roles may delete
$allowed = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'BILLING_CLERK'];
if (!in_array($_SESSION['role_code'], $allowed)) {
    echo json_encode(['success' => false, 'message' => 'You do not have permission to delete invoices.']);
    exit();
}

// Parse JSON body
$input = json_decode(file_get_contents('php://input'), true);
if (empty($input['invoice_ids']) || !is_array($input['invoice_ids'])) {
    echo json_encode(['success' => false, 'message' => 'No invoice IDs provided.']);
    exit();
}

// Sanitise IDs — integers only
$ids = array_map('intval', $input['invoice_ids']);
$ids = array_filter($ids, fn($id) => $id > 0);
if (empty($ids)) {
    echo json_encode(['success' => false, 'message' => 'Invalid invoice IDs.']);
    exit();
}

$deleted = 0;
$skipped = 0;
$errors  = [];

$conn->begin_transaction();

try {
    foreach ($ids as $invoice_id) {
        // Fetch invoice — verify it exists and check payment status
        $stmt = $conn->prepare("SELECT invoice_id, invoice_number, amount_paid, status FROM invoices WHERE invoice_id = ?");
        $stmt->bind_param("i", $invoice_id);
        $stmt->execute();
        $invoice = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if (!$invoice) {
            $skipped++;
            continue; // Already gone or never existed
        }

        // Protect invoices that have any payment recorded
        if ((float)$invoice['amount_paid'] > 0 || $invoice['status'] === 'PAID') {
            $skipped++;
            $errors[] = $invoice['invoice_number'] . ' (has payments)';
            continue;
        }

        // Delete related invoice items first (FK integrity)
        $del_items = $conn->prepare("DELETE FROM invoice_items WHERE invoice_id = ?");
        $del_items->bind_param("i", $invoice_id);
        $del_items->execute();
        $del_items->close();

        // Delete the invoice itself
        $del_inv = $conn->prepare("DELETE FROM invoices WHERE invoice_id = ?");
        $del_inv->bind_param("i", $invoice_id);
        $del_inv->execute();
        $del_inv->close();

        // Audit log
        $log_stmt = $conn->prepare(
            "INSERT INTO audit_logs (user_id, action, entity_type, entity_id, description, ip_address, user_agent, created_at)
             VALUES (?, 'DELETE', 'INVOICE', ?, ?, ?, ?, NOW())"
        );
        $log_user    = (int)$_SESSION['user_id'];
        $log_desc    = 'Deleted invoice ' . $invoice['invoice_number'];
        $log_ip      = $_SERVER['REMOTE_ADDR']     ?? null;
        $log_agent   = $_SERVER['HTTP_USER_AGENT'] ?? null;
        $log_stmt->bind_param("iisss", $log_user, $invoice_id, $log_desc, $log_ip, $log_agent);
        $log_stmt->execute();
        $log_stmt->close();

        $deleted++;
    }

    $conn->commit();

    echo json_encode([
        'success' => true,
        'deleted' => $deleted,
        'skipped' => $skipped,
        'message' => "$deleted invoice(s) deleted successfully." . ($skipped > 0 ? " $skipped skipped (payments exist)." : ''),
    ]);

} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}

mysqli_close($conn);