<?php
declare(strict_types=1);

require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/../src/MultiTenant/TenantManager.php';
require_once __DIR__ . '/../src/DatabaseHelper.php';
require_once __DIR__ . '/../src/FileManager.php';
require_once __DIR__ . '/../src/Contract.php';
require_once __DIR__ . '/../src/Invoice.php';

// Require authentication (skipped for receipt PDFs)
// AuthManager::requireAuth(); // Moved after action definition

// Initialize tenant context
TenantManager::initialize();

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

// Resolve workspace context
$companyId = null;
if (isset($_GET['workspace'])) {
    $workspaceParam = sanitizeText($_GET['workspace']);
    $pdo = getPDO();
    $stmt = $pdo->prepare('SELECT id FROM companies WHERE username = ?');
    $stmt->execute([$workspaceParam]);
    $company = $stmt->fetch();
    $companyId = $company['id'] ?? null;
}
if (!$companyId) {
    $companyId = TenantDB::getTenant();
}

// Additional fallback: try to get user's default workspace
if (!$companyId) {
    try {
        $pdo = getPDO();
        // Get user's first available workspace
        $stmt = $pdo->prepare('SELECT c.id FROM companies c 
            JOIN user_company_access uca ON c.id = uca.company_id 
            WHERE uca.user_id = ? LIMIT 1');
        $stmt->execute([$_SESSION['user_id'] ?? 0]);
        $company = $stmt->fetch();
        $companyId = $company['id'] ?? null;
    } catch (Exception $e) {
        // Ignore errors, will show proper error message below
    }
}

// Set tenant context
if ($companyId) {
    TenantDB::setTenant($companyId);
} else {
    // No workspace context available - show error
    http_response_code(400);
    echo '<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Workspace Required</title>
    <link rel="stylesheet" href="/assets/styles/app.build.css">
</head>
<body class="bg-slate-100 min-h-screen flex items-center justify-center">
    <div class="bg-white rounded-lg shadow-lg p-8 max-w-md w-full mx-4">
        <div class="text-center">
            <div class="w-16 h-16 bg-amber-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <svg class="w-8 h-8 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"></path>
                </svg>
            </div>
            <h1 class="text-2xl font-bold text-slate-900 mb-2">Workspace Required</h1>
            <p class="text-slate-600 mb-6">Please access this page from within a workspace context.</p>
            <div class="space-y-3">
                <a href="/index.php" class="block w-full px-4 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700 transition-colors duration-200">
                    Go to Dashboard
                </a>
                <a href="/proposals.php" class="block w-full px-4 py-2 border border-slate-300 text-slate-700 rounded-lg hover:bg-slate-50 transition-colors duration-200">
                    View Proposals
                </a>
            </div>
        </div>
    </div>
</body>
</html>';
    exit;
}

$proposalId = (int) ($_GET['proposal_id'] ?? 0);
$contractId = (int) ($_GET['contract_id'] ?? 0);
$invoiceId = (int) ($_GET['invoice_id'] ?? 0);
$action = $_GET['action'] ?? '';

// Require authentication (skipped for receipt PDFs)
if ($action !== 'view_payment_receipt') {
    AuthManager::requireAuth();
}

// Handle payment receipts
if ($action === 'view_payment_receipt' && $invoiceId > 0 && !empty($_GET['payment_id'])) {
    $paymentId = (int) $_GET['payment_id'];
    
    require_once __DIR__ . '/../src/Invoice.php';
    $invoice = Invoice::find($invoiceId);
    if (!$invoice) {
        http_response_code(404);
        echo 'Invoice not found.';
        exit;
    }
    
    // Get the specific payment
    $pdo = getPDO();
    $stmt = $pdo->prepare('SELECT * FROM invoice_payments WHERE id = ? AND invoice_id = ?');
    $stmt->execute([$paymentId, $invoiceId]);
    $payment = $stmt->fetch();
    
    if (!$payment) {
        http_response_code(404);
        echo 'Payment not found.';
        exit;
    }
    
    // Get all payments for this invoice to show history
    $stmt = $pdo->prepare('SELECT * FROM invoice_payments WHERE invoice_id = ? ORDER BY payment_date DESC');
    $stmt->execute([$invoiceId]);
    $payments = $stmt->fetchAll();
    
    // Get invoice items
    $invoiceItems = Invoice::getInvoiceItems($invoiceId);
    $settings = InvoiceSettings::get() ?? [];
    
    // Prepare data for receipt template
    $invoiceData = [
        'id' => $invoice['id'],
        'invoice_number' => $invoice['invoice_number'],
        'issue_date' => $invoice['issue_date'],
        'due_date' => $invoice['due_date'],
        'invoice_subject' => $invoice['invoice_subject'] ?? '',
        'project_id' => $invoice['project_id'] ?? null,
        'proposal_id' => $invoice['proposal_id'] ?? null,
        'contract_id' => $invoice['contract_id'] ?? null,
        'notes' => $invoice['notes'] ?? '',
        'payment_terms' => $invoice['payment_terms'] ?? '',
        'tax_type' => $invoice['tax_type'] ?? 'per_item',
        'tax_exempt' => $invoice['tax_exempt'] ?? false,
        'tax_exemption_reason' => $invoice['tax_exemption_reason'] ?? '',
        'invoice_level_tax_bracket_id' => $invoice['invoice_level_tax_bracket_id'] ?? null,
        'subtotal' => $invoice['subtotal'],
        'tax_total' => $invoice['tax_amount'],
        'total' => $invoice['total'],
        'client_info' => [
            'name' => $invoice['client_name'],
            'email' => $invoice['client_email'] ?? '',
            'phone' => $invoice['client_phone'] ?? '',
            'address' => $invoice['client_address'] ?? '',
            'company_name' => $invoice['client_company_name'] ?? null
        ],
        'display_name' => $invoice['display_name'] ?? null,
        'display_name_option' => $invoice['display_name_option'] ?? 'client_name',
        'custom_display_name' => $invoice['custom_display_name'] ?? null,
        'items' => array_map(function($item) {
            return [
                'item_name' => $item['description'],
                'description' => $item['description'],
                'quantity' => $item['quantity'],
                'unit_price' => $item['unit_price'],
                'discount_percent' => 0, // No discount column in invoice_items
                'tax_amount' => $item['total'] * ($item['tax_rate'] / 100), // Calculate tax amount
                'tax_bracket_name' => $item['tax_bracket_name'] ?? null,
                'tax_bracket_rate' => $item['tax_rate'] ?? 0,
                'total' => $item['total']
            ];
        }, $invoiceItems)
    ];
    
    // Generate HTML receipt
    ob_start();
    include __DIR__ . '/../templates/payment_receipt_template.php';
    $receiptHtml = ob_get_clean();
    
    // Generate PDF using Node.js script
    $receiptNumber = 'R-' . $invoice['invoice_number'] . '-' . $paymentId;
    $pdfFilename = 'Receipt-' . $receiptNumber . '.pdf';
    
    // Use company-specific storage
    $pdfPath = FileManager::getFilePath($companyId, 'receipts', $pdfFilename);
    
    // Ensure company directories exist
    FileManager::ensureCompanyDirectories($companyId);
    
    // Generate PDF using Node.js
    $nodeScript = __DIR__ . '/../src/generate_receipt_pdf.js';
    $tempHtmlFile = sys_get_temp_dir() . '/receipt_' . $receiptNumber . '.html';
    file_put_contents($tempHtmlFile, $receiptHtml);
    
    $command = "node " . escapeshellarg($nodeScript) . " " . escapeshellarg($tempHtmlFile) . " " . escapeshellarg($pdfPath) . " 2>&1";
    $output = shell_exec($command);
    
    // Clean up temporary HTML file
    unlink($tempHtmlFile);
    
    // Check if PDF was generated successfully
    if (!file_exists($pdfPath) || filesize($pdfPath) === 0) {
        // Fallback to HTML if PDF generation fails
        header('Content-Type: text/html; charset=utf-8');
        header('Content-Disposition: inline; filename="Receipt-' . $receiptNumber . '.html"');
        echo $receiptHtml;
        exit;
    }
    
    // Set headers for PDF download
    header('Content-Type: application/pdf');
    header('Content-Length: ' . filesize($pdfPath));
    header('Content-Disposition: inline; filename="Receipt-' . $receiptNumber . '.pdf"');
    
    readfile($pdfPath);
    exit;
}

// Handle invoices - generate on-the-fly like receipts
if ($invoiceId > 0 && in_array($action, ['download', 'view_invoice'])) {
    require_once __DIR__ . '/../src/Invoice.php';
    $invoice = Invoice::find($invoiceId);
    
    if (!$invoice) {
        http_response_code(404);
        echo 'Invoice not found.';
        exit;
    }
    
    // Get invoice items
    $invoiceItems = Invoice::getInvoiceItems($invoiceId);
    $settings = InvoiceSettings::get() ?? [];
    
    // Prepare data for invoice template (same format as receipt)
    $invoiceData = [
        'invoice_number' => $invoice['invoice_number'],
        'issue_date' => $invoice['issue_date'],
        'due_date' => $invoice['due_date'],
        'subtotal' => $invoice['subtotal'],
        'tax_total' => $invoice['tax_amount'],
        'total' => $invoice['total'],
        'client_name' => $invoice['client_name'],
        'client_email' => $invoice['client_email'] ?? '',
        'client_phone' => $invoice['client_phone'] ?? '',
        'client_address' => $invoice['client_address'] ?? '',
        'notes' => $invoice['notes'] ?? '',
        'items' => array_map(function($item) {
            return [
                'item_name' => $item['description'],
                'description' => $item['description'],
                'quantity' => $item['quantity'],
                'unit_price' => $item['unit_price'],
                'discount_percent' => 0,
                'tax_amount' => $item['total'] * ($item['tax_rate'] / 100),
                'tax_bracket_name' => $item['tax_bracket_name'] ?? null,
                'tax_bracket_rate' => $item['tax_rate'] ?? 0,
                'total' => $item['total']
            ];
        }, $invoiceItems)
    ];
    
    // Generate HTML invoice
    ob_start();
    include __DIR__ . '/../templates/invoice_template.php';
    $invoiceHtml = ob_get_clean();
    
    // Generate PDF using Node.js (same method as receipts)
    $pdfFilename = 'Invoice-' . $invoice['invoice_number'] . '.pdf';
    $pdfPath = FileManager::getFilePath($companyId, 'invoices', $pdfFilename);
    
    // Ensure company directories exist
    FileManager::ensureCompanyDirectories($companyId);
    
    // Generate PDF using Node.js
    $nodeScript = __DIR__ . '/../src/generate_receipt_pdf.js';
    $tempHtmlFile = sys_get_temp_dir() . '/invoice_' . $invoice['invoice_number'] . '.html';
    file_put_contents($tempHtmlFile, $invoiceHtml);
    
    $command = "node " . escapeshellarg($nodeScript) . " " . escapeshellarg($tempHtmlFile) . " " . escapeshellarg($pdfPath) . " 2>&1";
    $output = shell_exec($command);
    
    // Clean up temporary HTML file
    unlink($tempHtmlFile);
    
    // Check if PDF was generated successfully
    if (!file_exists($pdfPath) || filesize($pdfPath) === 0) {
        // Fallback to HTML if PDF generation fails
        header('Content-Type: text/html; charset=utf-8');
        header('Content-Disposition: inline; filename="Invoice-' . $invoice['invoice_number'] . '.html"');
        echo $invoiceHtml;
        exit;
    }
    
    // Set headers for PDF download (same as receipts)
    header('Content-Type: application/pdf');
    header('Content-Length: ' . filesize($pdfPath));
    header('Content-Disposition: inline; filename="Invoice-' . $invoice['invoice_number'] . '.pdf"');
    
    readfile($pdfPath);
    exit;
}

// Handle proposals - use company-specific storage
if ($proposalId > 0 && ($action === 'download' || $action === 'view')) {
    require_once __DIR__ . '/../src/Proposal.php';
    $proposal = Proposal::find($proposalId);
    if (!$proposal) {
        http_response_code(404);
        echo 'Proposal not found.';
        exit;
    }
    
    // Generate PDF if it doesn't exist or if force=1 is set
    $forceRegenerate = isset($_GET['force']) && $_GET['force'] === '1';
    if (!$proposal['pdf_path'] || !file_exists(FileManager::getFilePath($companyId, 'proposals', basename($proposal['pdf_path']))) || $forceRegenerate) {
        try {
            $pdfPath = Proposal::generatePdf($proposalId);
            // Reload proposal to get updated PDF path
            $proposal = Proposal::find($proposalId);
        } catch (Exception $e) {
            http_response_code(500);
            echo 'Error generating PDF: ' . $e->getMessage();
            exit;
        }
    }
    
    if (!$proposal['pdf_path']) {
        http_response_code(500);
        echo 'PDF file not available.';
        exit;
    }
    
    // Use company-specific storage
    $pdfFilename = basename($proposal['pdf_path']);
    $pdfPath = FileManager::getFilePath($companyId, 'proposals', $pdfFilename);
    
    if (!file_exists($pdfPath)) {
        http_response_code(404);
        echo 'PDF file not found.';
        exit;
    }
    
    // Set headers for PDF download/view
    header('Content-Type: application/pdf');
    header('Content-Length: ' . filesize($pdfPath));
    
    $proposalNumber = $proposal['proposal_number'] ?? 'PRO-' . $proposalId;
    $sanitizedFilename = preg_replace('/[^a-zA-Z0-9\-_]/', '_', $proposalNumber);
    
    if ($action === 'download') {
        header('Content-Disposition: attachment; filename="' . $sanitizedFilename . '.pdf"');
    } else {
        header('Content-Disposition: inline; filename="' . $sanitizedFilename . '.pdf"');
    }
    
    readfile($pdfPath);
    exit;
}

// Handle contracts - use company-specific storage
if ($contractId > 0 && in_array($action, ['download', 'view'])) {
    require_once __DIR__ . '/../src/Contract.php';
    
    // Get workspace-aware company ID
    $pdo = getPDO();
    $companyId = null;
    $workspaceParam = $_GET['workspace'] ?? null;
    if ($workspaceParam) {
        $stmt = $pdo->prepare("SELECT id FROM companies WHERE username = ?");
        $stmt->execute([$workspaceParam]);
        $company = $stmt->fetch();
        $companyId = $company['id'] ?? null;
    }
    
    // Fallback to tenant context
    if (!$companyId) {
        $companyId = TenantDB::getTenant();
    }
    
    if (!$companyId) {
        http_response_code(400);
        echo 'No workspace context available.';
        exit;
    }
    
    $contract = Contract::find($contractId);
    if (!$contract) {
        http_response_code(404);
        echo 'Contract not found.';
        exit;
    }
    
    // Use company-specific storage
    if (!empty($contract['pdf_path'])) {
        $pdfFilename = basename($contract['pdf_path']);
        $pdfPath = FileManager::getFilePath($companyId, 'contracts', $pdfFilename);
        
        if (file_exists($pdfPath)) {
            header('Content-Type: application/pdf');
            header('Content-Length: ' . filesize($pdfPath));
            $disposition = $action === 'download' ? 'attachment' : 'inline';
            header('Content-Disposition: ' . $disposition . '; filename="' . ($contract['contract_number'] ?? 'contract_' . $contractId) . '.pdf"');
            readfile($pdfPath);
            exit;
        }
    }
    
    // Generate contract PDF if it doesn't exist
    try {
        $pdfPath = Contract::generatePdf($contractId);
        $pdfFilename = basename($pdfPath);
        $fullPath = FileManager::getFilePath($companyId, 'contracts', $pdfFilename);
        
        if (file_exists($fullPath)) {
            header('Content-Type: application/pdf');
            header('Content-Length: ' . filesize($fullPath));
            $disposition = $action === 'download' ? 'attachment' : 'inline';
            header('Content-Disposition: ' . $disposition . '; filename="' . ($contract['contract_number'] ?? 'contract_' . $contractId) . '.pdf"');
            readfile($fullPath);
            exit;
        }
    } catch (Exception $e) {
        http_response_code(500);
        echo 'Error generating contract PDF: ' . $e->getMessage();
        exit;
    }
}

http_response_code(400);
echo 'Invalid request.';
?>