<?php
// Turn off error output to prevent corrupting PDF
error_reporting(E_ALL);
ini_set('display_errors', 0);
ob_clean(); // Clean any previous output buffer

session_start();
require_once 'includes/auth.php';
requireLogin();
require_once 'config/database.php';
require_once 'includes/functions.php';

// Load TCPDF
require_once 'tcpdf/tcpdf.php';

$id = $_GET['id'] ?? 0;
if (!$id) die('Invalid document ID.');

$userId = $_SESSION['user_id'];
$stmt = $pdo->prepare("SELECT * FROM companies WHERE user_id = ? LIMIT 1");
$stmt->execute([$userId]);
$company = $stmt->fetch();
if (!$company) die('Company not found.');

$stmt = $pdo->prepare("SELECT d.*, c.name as client_name, c.email as client_email, c.phone as client_phone, c.address as client_address, c.city as client_city, c.state as client_state, c.country as client_country FROM documents d LEFT JOIN clients c ON d.client_id = c.id WHERE d.id = ? AND d.company_id = ?");
$stmt->execute([$id, $company['id']]);
$document = $stmt->fetch();
if (!$document) die('Document not found.');

$stmt = $pdo->prepare("SELECT * FROM document_items WHERE document_id = ?");
$stmt->execute([$id]);
$items = $stmt->fetchAll();

// Create PDF
class MYPDF extends TCPDF {
    public function Header() {}
    public function Footer() {}
}

$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 10);

// Build HTML
$html = '';

// Header
$html .= '<table width="100%" cellpadding="5" style="border-bottom: 1px solid #ccc; margin-bottom: 20px;">';
$html .= '<tr>';
$html .= '<td width="50%" style="text-align: left;">';
if (!empty($company['logo']) && file_exists($company['logo'])) {
    // Convert relative path to absolute
    $logo_abs = realpath($company['logo']);
    if ($logo_abs) {
        // Suppress GD warnings for PNG profiles
        $html .= '<img src="' . $logo_abs . '" height="50"><br>';
    }
}
$html .= '<strong style="font-size: 16px;">' . htmlspecialchars($company['name']) . '</strong><br>';
if ($company['address']) $html .= nl2br(htmlspecialchars($company['address'])) . '<br>';
if ($company['phone']) $html .= 'Tel: ' . htmlspecialchars($company['phone']) . '<br>';
if ($company['email']) $html .= 'Email: ' . htmlspecialchars($company['email']);
$html .= '</td>';
$html .= '<td width="50%" style="text-align: right;">';
$html .= '<strong style="font-size: 20px;">' . strtoupper(htmlspecialchars($document['type'])) . '</strong><br>';
$html .= '<strong>' . htmlspecialchars($document['document_number']) . '</strong><br>';
$html .= 'Issue Date: ' . date('M d, Y', strtotime($document['issue_date'])) . '<br>';
if ($document['due_date']) $html .= 'Due Date: ' . date('M d, Y', strtotime($document['due_date']));
$html .= '</td>';
$html .= '</tr>';
$html .= '</table>';

// Bill To
$html .= '<table width="100%" cellpadding="5" style="margin-bottom: 20px; background-color: #f9fafb;">';
$html .= '<tr>';
$html .= '<td><strong>Bill To:</strong><br>';
$html .= htmlspecialchars($document['client_name']) . '<br>';
if ($document['client_address']) $html .= nl2br(htmlspecialchars($document['client_address'])) . '<br>';
$city_state = '';
if ($document['client_city']) $city_state .= htmlspecialchars($document['client_city']);
if ($document['client_state']) $city_state .= ($city_state ? ', ' : '') . htmlspecialchars($document['client_state']);
if ($city_state) $html .= $city_state . '<br>';
if ($document['client_country']) $html .= htmlspecialchars($document['client_country']) . '<br>';
if ($document['client_email']) $html .= 'Email: ' . htmlspecialchars($document['client_email']);
$html .= '</td>';
$html .= '</table>';

// Items Table
$html .= '<table border="1" cellpadding="6" style="border-collapse: collapse; width: 100%;">';
$html .= '<thead><tr style="background-color: #f3f4f6;">
            <th width="50%">Item</th>
            <th width="10%" align="right">Qty</th>
            <th width="15%" align="right">Price</th>
            <th width="10%" align="right">Tax</th>
            <th width="15%" align="right">Total</th>
            </tr></thead><tbody>';
foreach ($items as $item) {
    $html .= '<tr>
                <td>' . htmlspecialchars($item['description']) . '</td>
                <td align="right">' . $item['quantity'] . '</td>
                <td align="right">' . formatMoney($item['unit_price'], $document['currency']) . '</td>
                <td align="right">' . $item['tax_rate'] . '%</td>
                <td align="right">' . formatMoney($item['total'], $document['currency']) . '</td>
              </tr>';
}
$html .= '</tbody><tfoot>';
$html .= '<tr><td colspan="4" align="right"><strong>Subtotal:</strong></td><td align="right">' . formatMoney($document['subtotal'], $document['currency']) . '</td></tr>';
if ($document['discount_amount'] > 0) {
    $html .= '<tr><td colspan="4" align="right"><strong>Discount:</strong></td><td align="right">- ' . formatMoney($document['discount_amount'], $document['currency']) . '</td></tr>';
}
$html .= '<tr><td colspan="4" align="right"><strong>Tax:</strong></td><td align="right">' . formatMoney($document['tax_amount'], $document['currency']) . '</td></tr>';
$html .= '<tr style="border-top: 2px solid #000;"><td colspan="4" align="right"><strong>Total:</strong></td><td align="right"><strong>' . formatMoney($document['total'], $document['currency']) . '</strong></td></tr>';
$html .= '</tfoot></table>';

if ($document['notes']) {
    $html .= '<div style="margin-top: 20px;"><strong>Notes:</strong><br>' . nl2br(htmlspecialchars($document['notes'])) . '</div>';
}
if ($document['terms']) {
    $html .= '<div style="margin-top: 10px;"><strong>Terms & Conditions:</strong><br>' . nl2br(htmlspecialchars($document['terms'])) . '</div>';
}

// Output PDF (suppress all warnings during write)
$old_error = error_reporting(0);
$pdf->writeHTML($html, true, false, true, false, '');
error_reporting($old_error);

// Clear any extra output and send PDF
ob_end_clean(); // Clear any remaining buffer
$pdf->Output($document['type'] . '_' . $document['document_number'] . '.pdf', 'I');
exit;
?>