37684-vm/api/generate_invoice_pdf.php
2026-03-01 22:19:37 +00:00

91 lines
2.9 KiB
PHP

<?php
session_start();
if (!isset($_SESSION["user_id"])) {
header("Location: ../login.php");
exit;
}
if (!isset($_GET['id'])) {
die("Invoice ID required.");
}
require_once __DIR__ . '/../db/config.php';
$db = db();
// Fetch invoice and ensure it belongs to the user
$stmt = $db->prepare("SELECT i.*, u.name as user_name, u.email as user_email
FROM invoices i
JOIN users u ON i.user_id = u.id
WHERE i.id = ? AND i.user_id = ?");
$stmt->execute([$_GET['id'], $_SESSION['user_id']]);
$invoice = $stmt->fetch();
if (!$invoice) {
die("Invoice not found.");
}
require_once __DIR__ . '/../fpdf/fpdf.php';
class InvoicePDF extends FPDF {
function Header() {
$project_name = $_SERVER['PROJECT_NAME'] ?? 'LPA Online';
$this->SetFont('Arial', 'B', 15);
$this->Cell(80);
$this->Cell(30, 10, strtoupper($project_name), 0, 0, 'C');
$this->Ln(20);
}
function Footer() {
$this->SetY(-15);
$this->SetFont('Arial', 'I', 8);
$this->Cell(0, 10, 'Page ' . $this->PageNo() . '/{nb}', 0, 0, 'C');
}
}
$pdf = new InvoicePDF();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Arial', 'B', 16);
$pdf->Cell(0, 10, 'INVOICE', 0, 1, 'L');
$pdf->SetFont('Arial', '', 10);
$pdf->Cell(0, 10, 'Invoice Number: #' . $invoice['invoice_number'], 0, 1, 'L');
$pdf->Cell(0, 10, 'Date: ' . date('M d, Y', strtotime($invoice['created_at'])), 0, 1, 'L');
$pdf->Ln(5);
$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(0, 10, 'Billed To:', 0, 1, 'L');
$pdf->SetFont('Arial', '', 10);
$pdf->Cell(0, 10, ($invoice['user_name'] ?: 'N/A'), 0, 1, 'L');
$pdf->Cell(0, 10, $invoice['user_email'], 0, 1, 'L');
$pdf->Ln(10);
// Table Header
$pdf->SetFillColor(240, 240, 240);
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(130, 10, 'Description', 1, 0, 'L', true);
$pdf->Cell(60, 10, 'Amount', 1, 1, 'R', true);
// Table Body
$pdf->SetFont('Arial', '', 10);
$items = json_decode($invoice['items_json'] ?? '[]', true);
if (empty($items)) {
$pdf->Cell(130, 10, $invoice['credits_added'] . ' LPA Credits', 1, 0, 'L');
$pdf->Cell(60, 10, ($invoice['currency'] === 'GBP' ? '£' : $invoice['currency']) . number_format($invoice['amount'], 2), 1, 1, 'R');
} else {
foreach ($items as $item) {
$pdf->Cell(130, 10, $item['name'], 1, 0, 'L');
$pdf->Cell(60, 10, ($invoice['currency'] === 'GBP' ? '£' : $invoice['currency']) . number_format($item['amount'], 2), 1, 1, 'R');
}
}
// Total
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(130, 10, 'Total Paid', 1, 0, 'R');
$pdf->Cell(60, 10, ($invoice['currency'] === 'GBP' ? '£' : $invoice['currency']) . number_format($invoice['amount'], 2), 1, 1, 'R');
$pdf->Ln(20);
$pdf->SetFont('Arial', 'I', 10);
$pdf->Cell(0, 10, 'Thank you for your business.', 0, 1, 'C');
$pdf->Output('I', 'Invoice-' . $invoice['invoice_number'] . '.pdf');