<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';

$id = (int)($_GET['id'] ?? 0);
if (!$id) { die('Invalid invoice ID.'); }

$pdo = getDB();
$stmt = $pdo->prepare("
    SELECT si.*, c.name as customer_name, c.phone as customer_phone, c.email as customer_email, c.address as customer_address,
           u.name as created_by_name
    FROM sales_invoices si
    LEFT JOIN customers c ON si.customer_id = c.id
    LEFT JOIN users u ON si.created_by = u.id
    WHERE si.id = ?
");
$stmt->execute([$id]);
$invoice = $stmt->fetch();
if (!$invoice) { die('Invoice not found.'); }

$stmt = $pdo->prepare("
    SELECT sii.*, p.product_name as product_name, p.model, p.product_type, pi.imei_number
    FROM sales_invoice_items sii
    JOIN products p ON sii.product_id = p.id
    LEFT JOIN product_imei pi ON sii.imei_id = pi.id
    WHERE sii.sales_invoice_id = ?
");
$stmt->execute([$id]);
$items = $stmt->fetchAll();

$shop_name = getSetting('shop_name', 'DigiMobiz Mobile Shop');
$shop_address = getSetting('shop_address', '');
$shop_phone = getSetting('shop_phone', '');
$shop_email = getSetting('shop_email', '');
$currency_symbol = getSetting('currency_symbol', 'Rs.');
$invoice_terms = getSetting('invoice_terms', '');

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3 no-print">
            <h4 class="page-title mb-0"><i class="fas fa-file-invoice me-2"></i>Invoice #<?= htmlspecialchars($invoice['invoice_no']) ?></h4>
            <div>
                <button class="btn btn-primary" onclick="window.print()"><i class="fas fa-print me-1"></i>Print</button>
                <a href="<?= BASE_URL ?>pos/print_invoice.php?id=<?= $id ?>" class="btn btn-info" target="_blank"><i class="fas fa-receipt me-1"></i>Thermal</a>
                <a href="<?= BASE_URL ?>pos/pos.php" class="btn btn-secondary"><i class="fas fa-arrow-left me-1"></i>Back to POS</a>
            </div>
        </div>

        <div class="card">
            <div class="card-body" id="invoiceArea">
                <div class="text-center mb-4">
                    <img src="<?= htmlspecialchars(getShopLogoUrl()) ?>?v=<?= time() ?>" alt="Logo" style="max-height:60px;margin-bottom:5px;" onerror="this.style.display='none'">
                    <h3 class="fw-bold"><?= htmlspecialchars($shop_name) ?></h3>
                    <p class="mb-0"><?= nl2br(htmlspecialchars($shop_address)) ?></p>
                    <p class="mb-0">Phone: <?= htmlspecialchars($shop_phone) ?> | Email: <?= htmlspecialchars($shop_email) ?></p>
                </div>
                <hr>
                <div class="row mb-4">
                    <div class="col-6">
                        <strong>Invoice To:</strong><br>
                        <?php if ($invoice['customer_name']): ?>
                            <?= htmlspecialchars($invoice['customer_name']) ?><br>
                            <?= htmlspecialchars($invoice['customer_phone'] ?? '') ?><br>
                            <?= nl2br(htmlspecialchars($invoice['customer_address'] ?? '')) ?>
                        <?php else: ?>
                            Walk-in Customer
                        <?php endif; ?>
                    </div>
                    <div class="col-6 text-end">
                        <strong>Invoice #:</strong> <?= htmlspecialchars($invoice['invoice_no']) ?><br>
                        <strong>Date:</strong> <?= date('Y-m-d h:i A', strtotime($invoice['invoice_date'])) ?><br>
                        <strong>Status:</strong> <?= getStatusBadge($invoice['invoice_status']) ?><br>
                        <strong>Sales Person:</strong> <?= htmlspecialchars($invoice['created_by_name'] ?? '-') ?>
                    </div>
                </div>

                <table class="table table-bordered">
                    <thead class="table-light">
                        <tr>
                            <th>#</th>
                            <th>Product</th>
                            <th>IMEI</th>
                            <th>Qty</th>
                            <th>Price</th>
                            <th>Total</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $i = 1; foreach ($items as $item): ?>
                        <tr>
                            <td><?= $i++ ?></td>
                            <td><?= htmlspecialchars($item['product_name']) ?><?= $item['model'] ? ' (' . htmlspecialchars($item['model']) . ')' : '' ?></td>
                            <td><code><?= htmlspecialchars($item['imei_number'] ?? '-') ?></code></td>
                            <td><?= $item['quantity'] ?></td>
                            <td><?= formatCurrency($item['selling_price']) ?></td>
                            <td><?= formatCurrency($item['total_price']) ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>

                <div class="row">
                    <div class="col-6">
                        <p class="mb-0"><strong>Terms & Conditions:</strong></p>
                        <small><?= nl2br(htmlspecialchars($invoice_terms)) ?></small>
                    </div>
                    <div class="col-6">
                        <table class="table table-sm table-borderless text-end">
                            <tr><td>Subtotal:</td><td><?= formatCurrency($invoice['subtotal']) ?></td></tr>
                            <tr><td>Discount (<?= ($discount_value = (float)($invoice['discount_value'] ?? 0)) ? $discount_value . ($invoice['discount_type'] == 'Percentage' ? '%' : '') : '0' ?>):</td><td><?= formatCurrency($invoice['discount_amount']) ?></td></tr>
                            <tr><td>Tax:</td><td><?= formatCurrency($invoice['tax_amount']) ?></td></tr>
                            <tr class="fw-bold"><td>Total:</td><td><?= formatCurrency($invoice['total_amount']) ?></td></tr>
                            <tr><td>Paid:</td><td><?= formatCurrency($invoice['paid_amount']) ?></td></tr>
                            <tr class="text-danger"><td>Balance:</td><td><?= formatCurrency($invoice['due_amount']) ?></td></tr>
                        </table>
                    </div>
                </div>

                <hr>
                <p class="text-center text-muted mb-0"><small>Thank you for your business! Powered by DigiMobiz</small></p>
            </div>
        </div>
    </div>
</div>

<style>
@media print {
    .sidebar, .navbar, .footer, .no-print, .btn { display: none !important; }
    .content-wrapper { margin: 0 !important; padding: 0 !important; width: 100% !important; }
    .card { box-shadow: none !important; border: none !important; }
    #invoiceArea { padding: 0 !important; }
}
</style>

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