<?php
/**
 * Delete Invoice
 */

use App\Core\Database;
use App\Core\AuditLogger;
use App\Middleware\AuthMiddleware;
use App\Middleware\RoleMiddleware;

$decoded = RoleMiddleware::require(['super_admin', 'admin', 'accountant']);
$db = Database::getInstance();

$data = json_decode(file_get_contents('php://input'), true);
$id = $data['id'] ?? null;

if (!$id) {
    json_error('Invoice ID is required', 422);
}

try {
    $db->beginTransaction();

    $stmt = $db->prepare("SELECT * FROM invoices WHERE id = ? FOR UPDATE");
    $stmt->execute([$id]);
    $invoice = $stmt->fetch();

    if (!$invoice) json_error('Invoice not found', 404);

    // Super admin can delete anything. Others might only delete non-approved, but let's allow admin to delete.
    if ($decoded['role'] !== 'super_admin' && $invoice['tenant_id'] !== $decoded['tenant_id']) {
        json_error('Access denied', 403);
    }

    $db->prepare("DELETE FROM invoice_lines WHERE invoice_id = ?")->execute([$id]);
    $db->prepare("DELETE FROM jofotara_submissions WHERE invoice_id = ?")->execute([$id]);
    $db->prepare("DELETE FROM invoices WHERE id = ?")->execute([$id]);

    $db->commit();

    AuditLogger::log('invoice.deleted', 'invoice', $id, null, null, $decoded);

    json_success(null, 'تم حذف الفاتورة بنجاح');

} catch (\Exception $e) {
    if ($db->inTransaction()) $db->rollBack();
    error_log("Invoice Delete Error: " . $e->getMessage());
    json_error('فشل في حذف الفاتورة', 500);
}
