<?php
require "../config/database.php";
require "../includes/auth.php";
require "../includes/subscription_guard.php";

$invoiceId = (int)($_GET["invoice_id"] ?? 0);
if ($invoiceId <= 0) {
    http_response_code(422);
    header("Content-Type: application/json; charset=utf-8");
    echo json_encode(["success" => false, "error" => "invoice_id_required"]);
    exit;
}

$stmt = $pdo->prepare("
    SELECT *
    FROM payment_invoices
    WHERE id = ?
    LIMIT 1
");
$stmt->execute([$invoiceId]);
$invoice = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$invoice) {
    http_response_code(404);
    header("Content-Type: application/json; charset=utf-8");
    echo json_encode(["success" => false, "error" => "invoice_not_found"]);
    exit;
}

$isPublicInvoice = ((int)($invoice["company_id"] ?? 0) === 0) && ((int)($invoice["subscription_id"] ?? 0) === 0);

if (!$isPublicInvoice) {
    requireApiAuth();

    $user = $_SESSION["user"] ?? [];
    $userId = (int)($user["id"] ?? 0);
    $roleId = (int)($user["role_id"] ?? 0);

    if ($roleId !== 4 && $roleId !== 1) {
        http_response_code(403);
        header("Content-Type: application/json; charset=utf-8");
        echo json_encode(["success" => false, "error" => "company_or_admin_only"]);
        exit;
    }

    if ($roleId === 4 && (int)($invoice["company_id"] ?? 0) !== $userId) {
        http_response_code(403);
        header("Content-Type: application/json; charset=utf-8");
        echo json_encode(["success" => false, "error" => "forbidden_invoice"]);
        exit;
    }
}

function escv($v): string {
    return htmlspecialchars((string)$v, ENT_QUOTES, "UTF-8");
}

$companyName = (string)($invoice["company_name"] ?? "");
$companyAddress = (string)($invoice["company_address"] ?? "");
$companyTaxId = (string)($invoice["company_tax_id"] ?? "");
$amount = (string)($invoice["amount_due"] ?? "");
$reference = (string)($invoice["reference_number"] ?? "");
$deadline = (string)($invoice["payment_deadline"] ?? "");
$bank = (string)($invoice["bank_name"] ?? "");
$account = (string)($invoice["bank_account"] ?? "");
$swift = (string)($invoice["bank_swift"] ?? "");
$plan = (string)($invoice["selected_plan"] ?? "");

$qrText = "KONZONA|REF:$reference|AMOUNT:$amount|ACC:$account|SWIFT:$swift|DEADLINE:$deadline";
$qrImageUrl = "https://api.qrserver.com/v1/create-qr-code/?size=240x240&data=" . rawurlencode($qrText);

header("Content-Type: text/html; charset=utf-8");
header("X-Content-Type-Options: nosniff");

echo "<!DOCTYPE html>";
echo "<html><head><meta charset='utf-8'><title>Payment Slip #" . (int)$invoice["id"] . "</title>";
echo "<style>
body{font-family:Arial,Helvetica,sans-serif;color:#111;margin:20px}
h1{font-size:22px;margin:0 0 14px}
.wrap{border:1px solid #d9d9d9;padding:18px;border-radius:6px}
.grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.item{padding:8px 10px;background:#f8f8f8;border-radius:4px}
.label{font-weight:700}
.qr{margin-top:18px;display:flex;gap:18px;align-items:flex-start}
.small{font-size:12px;color:#555;word-break:break-all}
</style></head><body>";
echo "<div class='wrap'>";
echo "<h1>Payment Slip #" . (int)$invoice["id"] . "</h1>";
echo "<div class='grid'>";
echo "<div class='item'><span class='label'>Company:</span> " . escv($companyName) . "</div>";
echo "<div class='item'><span class='label'>Address:</span> " . escv($companyAddress) . "</div>";
echo "<div class='item'><span class='label'>PIB / Tax ID:</span> " . escv($companyTaxId !== "" ? $companyTaxId : "-") . "</div>";
echo "<div class='item'><span class='label'>Plan:</span> " . escv($plan) . "</div>";
echo "<div class='item'><span class='label'>Amount Due:</span> €" . escv($amount) . "</div>";
echo "<div class='item'><span class='label'>Reference Number:</span> " . escv($reference) . "</div>";
echo "<div class='item'><span class='label'>Payment Deadline:</span> " . escv($deadline) . "</div>";
echo "<div class='item'><span class='label'>Bank:</span> " . escv($bank) . "</div>";
echo "<div class='item'><span class='label'>Bank Account:</span> " . escv($account) . "</div>";
echo "<div class='item'><span class='label'>SWIFT:</span> " . escv($swift) . "</div>";
echo "</div>";
echo "<div class='qr'>";
echo "<img src='" . escv($qrImageUrl) . "' alt='QR code' width='220' height='220'>";
echo "<div><div class='label'>QR payload</div><div class='small'>" . escv($qrText) . "</div></div>";
echo "</div>";
echo "</div>";
echo "</body></html>";
?>
