<?php
declare(strict_types=1);

// Simple PDF viewer that requires workspace context
require_once __DIR__ . '/../src/db.php';

$workspace = $_GET['workspace'] ?? $_SESSION['workspace'] ?? null;
if (!$workspace) {
    http_response_code(400);
    echo 'Workspace required. Please access this page from within a workspace context.';
    exit;
}

$invoiceId = (int) ($_GET['invoice_id'] ?? 0);
$paymentId = (int) ($_GET['payment_id'] ?? 0);
$action = $_GET['action'] ?? 'view';

// Handle payment receipt
if ($action === 'payment_receipt') {
    if ($paymentId <= 0) {
        http_response_code(400);
        echo 'Invalid payment ID.';
        exit;
    }
    
    // Get company for workspace validation
    $pdo = getPDO();
    $stmt = $pdo->prepare('SELECT id FROM companies WHERE username = ?');
    $stmt->execute([$workspace]);
    $company = $stmt->fetch();
    
    if (!$company) {
        http_response_code(404);
        echo 'Workspace not found.';
        exit;
    }
    
    $companyId = $company['id'];
    
    // Get payment and validate it belongs to this company's invoice
    $stmt = $pdo->prepare('
        SELECT p.*, i.invoice_number, i.company_id 
        FROM invoice_payments p
        JOIN invoices i ON p.invoice_id = i.id
        WHERE p.id = ? AND i.company_id = ?
    ');
    $stmt->execute([$paymentId, $companyId]);
    $payment = $stmt->fetch();
    
    if (!$payment) {
        http_response_code(404);
        echo 'Payment not found.';
        exit;
    }
    
    // Generate receipt on-the-fly if not exists
    if (empty($payment['receipt_path']) || !file_exists($payment['receipt_path'])) {
        // For now, redirect to a receipt generation page or show a message
        http_response_code(501);
        echo 'Payment receipt generation is not yet implemented. Please contact support.';
        exit;
    }
    
    // Get receipt file path
    $receiptFilename = basename($payment['receipt_path']);
    require_once __DIR__ . '/../src/FileManager.php';
    $receiptPath = FileManager::getFilePath($companyId, 'receipts', $receiptFilename);
    
    if (!file_exists($receiptPath)) {
        http_response_code(404);
        echo 'Receipt file not found. The receipt may need to be regenerated.';
        exit;
    }
    
    // Set headers for PDF
    header('Content-Type: application/pdf');
    header('Content-Length: ' . filesize($receiptPath));
    header('Content-Disposition: inline; filename="Receipt-' . $payment['invoice_number'] . '-' . $paymentId . '.pdf"');
    
    readfile($receiptPath);
    exit;
}

// Handle invoice PDF
if ($invoiceId <= 0) {
    http_response_code(400);
    echo 'Invalid invoice ID.';
    exit;
}

// Get company for workspace validation
$pdo = getPDO();
$stmt = $pdo->prepare('SELECT id FROM companies WHERE username = ?');
$stmt->execute([$workspace]);
$company = $stmt->fetch();

if (!$company) {
    http_response_code(404);
    echo 'Workspace not found.';
    exit;
}

$companyId = $company['id'];

// Get invoice and validate it belongs to this company
$stmt = $pdo->prepare('SELECT * FROM invoices WHERE id = ? AND company_id = ?');
$stmt->execute([$invoiceId, $companyId]);
$invoice = $stmt->fetch();

if (!$invoice) {
    http_response_code(404);
    echo 'Invoice not found.';
    exit;
}

if (empty($invoice['pdf_path'])) {
    http_response_code(404);
    echo 'PDF not generated for this invoice.';
    exit;
}

// Get PDF filename and check both old and new paths
$pdfFilename = basename($invoice['pdf_path']);

// Try old path first (for backward compatibility)
$oldPdfPath = __DIR__ . '/../storage/pdfs/' . $pdfFilename;
if (file_exists($oldPdfPath)) {
    $pdfPath = $oldPdfPath;
} else {
    // Try new path (company-specific)
    require_once __DIR__ . '/../src/FileManager.php';
    $pdfPath = FileManager::getFilePath($companyId, 'invoices', $pdfFilename);
}

if (!file_exists($pdfPath)) {
    http_response_code(404);
    echo 'PDF file not found.';
    exit;
}

// Set headers for PDF
header('Content-Type: application/pdf');
header('Content-Length: ' . filesize($pdfPath));

if ($action === 'download') {
    header('Content-Disposition: attachment; filename="Invoice-' . $invoice['invoice_number'] . '.pdf"');
} else {
    header('Content-Disposition: inline; filename="Invoice-' . $invoice['invoice_number'] . '.pdf"');
}

readfile($pdfPath);
exit;
?>
