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

$id = $_GET['id'] ?? 0;
if (!$id) { header('Location: documents.php'); exit; }

$userId = $_SESSION['user_id'];
$stmt = $pdo->prepare("SELECT * FROM companies WHERE user_id = ? LIMIT 1");
$stmt->execute([$userId]);
$company = $stmt->fetch();
if (!$company) { header('Location: settings.php'); exit; }

$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) { header('Location: documents.php'); exit; }

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

$success_msg = $_SESSION['success'] ?? '';
$error_msg = $_SESSION['error'] ?? '';
unset($_SESSION['success'], $_SESSION['error']);

include 'includes/header.php';
?>

<?php if ($success_msg): ?>
    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-lg mb-4"><?php echo htmlspecialchars($success_msg); ?></div>
<?php endif; ?>
<?php if ($error_msg): ?>
    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg mb-4"><?php echo htmlspecialchars($error_msg); ?></div>
<?php endif; ?>

<div class="max-w-4xl mx-auto">
    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg overflow-hidden">
        <div class="bg-gradient-to-r from-blue-600 to-indigo-600 px-8 py-6 text-white">
            <div class="flex justify-between items-center">
                <div>
                    <?php if ($company['logo']): ?><img src="<?php echo htmlspecialchars($company['logo']); ?>" class="h-12 mb-2"><?php endif; ?>
                    <h1 class="text-2xl font-bold"><?php echo htmlspecialchars($company['name']); ?></h1>
                    <p class="text-blue-100 text-sm"><?php echo nl2br(htmlspecialchars($company['address'] ?? '')); ?></p>
                </div>
                <div class="text-right">
                    <h2 class="text-3xl font-bold uppercase"><?php echo ucfirst($document['type']); ?></h2>
                    <p class="text-xl"><?php echo htmlspecialchars($document['document_number']); ?></p>
                    <p class="text-sm text-blue-100">Issue Date: <?php echo date('M d, Y', strtotime($document['issue_date'])); ?></p>
                    <?php if ($document['due_date']): ?><p class="text-sm text-blue-100">Due Date: <?php echo date('M d, Y', strtotime($document['due_date'])); ?></p><?php endif; ?>
                </div>
            </div>
        </div>

        <div class="p-8">
            <div class="mb-8"><h3 class="text-lg font-semibold text-gray-800 dark:text-white mb-2">Bill To:</h3><p class="text-gray-700 dark:text-gray-300 font-medium"><?php echo htmlspecialchars($document['client_name']); ?></p><p class="text-gray-600 dark:text-gray-400"><?php echo nl2br(htmlspecialchars($document['client_address'] ?? '')); ?></p><?php if ($document['client_email']): ?><p class="text-gray-600 dark:text-gray-400"><?php echo htmlspecialchars($document['client_email']); ?></p><?php endif; ?></div>

            <div class="mb-8 overflow-x-auto"><table class="w-full"><thead><tr class="border-b border-gray-200 dark:border-gray-700"><th class="text-left py-3 text-gray-600 dark:text-gray-400">Item</th><th class="text-right py-3 text-gray-600 dark:text-gray-400">Qty</th><th class="text-right py-3 text-gray-600 dark:text-gray-400">Price</th><th class="text-right py-3 text-gray-600 dark:text-gray-400">Tax</th><th class="text-right py-3 text-gray-600 dark:text-gray-400">Total</th></tr></thead><tbody><?php foreach ($items as $item): ?><tr class="border-b border-gray-100 dark:border-gray-800"><td class="py-3 text-gray-800 dark:text-gray-200"><?php echo htmlspecialchars($item['description']); ?></td><td class="text-right text-gray-600 dark:text-gray-400"><?php echo $item['quantity']; ?></td><td class="text-right text-gray-600 dark:text-gray-400"><?php echo formatMoney($item['unit_price'], $document['currency']); ?></td><td class="text-right text-gray-600 dark:text-gray-400"><?php echo $item['tax_rate']; ?>%</td><td class="text-right font-semibold text-gray-800 dark:text-white"><?php echo formatMoney($item['total'], $document['currency']); ?></td></tr><?php endforeach; ?></tbody><tfoot><tr class="border-t border-gray-300 dark:border-gray-600"><td colspan="4" class="text-right py-2 font-semibold text-gray-700 dark:text-gray-300">Subtotal:</td><td class="text-right text-gray-800 dark:text-white"><?php echo formatMoney($document['subtotal'], $document['currency']); ?></td></tr><?php if ($document['discount_amount'] > 0): ?><tr><td colspan="4" class="text-right py-2 text-gray-700 dark:text-gray-300">Discount:</td><td class="text-right text-gray-800 dark:text-white">- <?php echo formatMoney($document['discount_amount'], $document['currency']); ?></td></tr><?php endif; ?><tr><td colspan="4" class="text-right py-2 text-gray-700 dark:text-gray-300">Tax:</td><td class="text-right text-gray-800 dark:text-white"><?php echo formatMoney($document['tax_amount'], $document['currency']); ?></td></tr><tr class="border-t border-gray-300 dark:border-gray-600"><td colspan="4" class="text-right py-2 font-bold text-lg text-gray-800 dark:text-white">Total:</td><td class="text-right font-bold text-lg text-gray-800 dark:text-white"><?php echo formatMoney($document['total'], $document['currency']); ?></td></tr></tfoot></table></div>

            <?php if ($document['notes']): ?><div class="mb-4"><h4 class="font-semibold text-gray-800 dark:text-white">Notes:</h4><p class="text-gray-600 dark:text-gray-400"><?php echo nl2br(htmlspecialchars($document['notes'])); ?></p></div><?php endif; ?>
            <?php if ($document['terms']): ?><div class="mb-4"><h4 class="font-semibold text-gray-800 dark:text-white">Terms & Conditions:</h4><p class="text-gray-600 dark:text-gray-400"><?php echo nl2br(htmlspecialchars($document['terms'])); ?></p></div><?php endif; ?>

            <div class="mt-8 flex flex-wrap justify-end space-x-3 gap-2">
                <?php if ($document['type'] == 'invoice'): ?>
                    <form method="POST" action="document-status.php" class="inline">
                        <input type="hidden" name="id" value="<?php echo $document['id']; ?>">
                        <input type="hidden" name="return_url" value="document-view.php?id=<?php echo $document['id']; ?>">
                        <select name="status" onchange="this.form.submit()" class="px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600">
                            <option value="draft" <?php echo $document['status'] == 'draft' ? 'selected' : ''; ?>>Draft</option>
                            <option value="sent" <?php echo $document['status'] == 'sent' ? 'selected' : ''; ?>>Sent</option>
                            <option value="paid" <?php echo $document['status'] == 'paid' ? 'selected' : ''; ?>>Paid</option>
                            <option value="partially_paid" <?php echo $document['status'] == 'partially_paid' ? 'selected' : ''; ?>>Partially Paid</option>
                            <option value="overdue" <?php echo $document['status'] == 'overdue' ? 'selected' : ''; ?>>Overdue</option>
                        </select>
                    </form>
                <?php endif; ?>
                <a href="document-pdf.php?id=<?php echo $document['id']; ?>" target="_blank" class="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"><i class="fas fa-file-pdf mr-2"></i>Download PDF</a>
                <a href="document-form.php?id=<?php echo $document['id']; ?>" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"><i class="fas fa-edit mr-2"></i>Edit</a>
                <a href="documents.php" class="px-4 py-2 border rounded-lg hover:bg-gray-100 dark:border-gray-600 dark:text-gray-300">Back</a>
            </div>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>