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

$pdo = getDB();
$id = (int)($_GET['id'] ?? 0);
if (!$id) { $_SESSION['error'] = 'Invalid purchase ID.'; header('Location: purchases.php'); exit; }

$stmt = $pdo->prepare("SELECT p.*, s.supplier_name, s.company_name, s.contact_person, s.phone as supplier_phone, s.email as supplier_email, s.address as supplier_address, u.name as created_by_name FROM purchases p LEFT JOIN suppliers s ON p.supplier_id = s.id LEFT JOIN users u ON p.created_by = u.id WHERE p.id = ?");
$stmt->execute([$id]);
$purchase = $stmt->fetch();
if (!$purchase) { $_SESSION['error'] = 'Purchase not found.'; header('Location: purchases.php'); exit; }

$items = $pdo->prepare("SELECT pi.*, p.product_code, p.product_name, p.product_type FROM purchase_items pi JOIN products p ON pi.product_id = p.id WHERE pi.purchase_id = ? ORDER BY pi.id");
$items->execute([$id]);
$items_list = $items->fetchAll();

$shop_name = getSetting('shop_name', 'DigiMobiz');
$shop_address = getSetting('shop_address', '');
$shop_phone = getSetting('shop_phone', '');
$shop_email = getSetting('shop_email', '');

$total_qty = 0;
foreach ($items_list as $item) { $total_qty += $item['quantity']; }

$currency_symbol = getSetting('currency_symbol', 'Rs.');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Purchase Invoice - <?= htmlspecialchars($purchase['purchase_no']) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        @media print {
            .no-print { display: none !important; }
            body { font-size: 12px; color: #000; }
            .invoice-box { border: 1px solid #ddd; padding: 20px; }
            .table thead th { background: #f8f9fa !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            .badge { border: 1px solid #000; }
            @page { margin: 15mm; }
        }
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #fff; color: #333; padding: 20px; }
        .invoice-box { max-width: 900px; margin: 0 auto; }
        .header { border-bottom: 2px solid #1a237e; padding-bottom: 15px; margin-bottom: 20px; }
        .header h2 { color: #1a237e; font-weight: 700; }
        .summary-table td { padding: 3px 10px; }
        .footer-text { text-align: center; margin-top: 30px; padding-top: 15px; border-top: 1px solid #ddd; font-size: 11px; color: #999; }
    </style>
</head>
<body>
    <div class="invoice-box">
        <div class="text-center no-print mb-3">
            <button class="btn btn-primary" onclick="window.print()"><i class="fas fa-print me-1"></i>Print</button>
            <a href="view_purchase.php?id=<?= $id ?>" class="btn btn-outline-secondary">Back</a>
        </div>

        <div class="header">
            <div class="row">
                <div class="col-6">
                    <img src="<?= htmlspecialchars(getShopLogoUrl()) ?>?v=<?= time() ?>" alt="Logo" style="max-height:50px;margin-bottom:5px;" onerror="this.style.display='none'">
                    <h2><?= htmlspecialchars($shop_name) ?></h2>
                    <p class="mb-0"><?= nl2br(htmlspecialchars($shop_address)) ?></p>
                    <p class="mb-0">Phone: <?= htmlspecialchars($shop_phone) ?></p>
                    <p class="mb-0">Email: <?= htmlspecialchars($shop_email) ?></p>
                </div>
                <div class="col-6 text-end">
                    <h3 class="text-muted">PURCHASE INVOICE</h3>
                    <h4 class="fw-bold"><?= htmlspecialchars($purchase['purchase_no']) ?></h4>
                    <p class="mb-0">Date: <?= formatDate($purchase['purchase_date']) ?></p>
                    <p class="mb-0">Status: <?= htmlspecialchars($purchase['purchase_status']) ?></p>
                </div>
            </div>
        </div>

        <div class="row mb-4">
            <div class="col-6">
                <strong>Supplier:</strong>
                <p class="mb-0"><?= htmlspecialchars($purchase['supplier_name']) ?></p>
                <?php if ($purchase['company_name']): ?><p class="mb-0"><?= htmlspecialchars($purchase['company_name']) ?></p><?php endif; ?>
                <p class="mb-0"><?= htmlspecialchars($purchase['contact_person'] ?? '') ?></p>
                <p class="mb-0"><?= htmlspecialchars($purchase['supplier_phone'] ?? '') ?></p>
                <p class="mb-0"><?= htmlspecialchars($purchase['supplier_address'] ?? '') ?></p>
            </div>
            <div class="col-6 text-end">
                <strong>Created By:</strong>
                <p class="mb-0"><?= htmlspecialchars($purchase['created_by_name'] ?? '-') ?></p>
                <?php if ($purchase['note']): ?><p class="mb-0"><strong>Note:</strong> <?= htmlspecialchars($purchase['note']) ?></p><?php endif; ?>
            </div>
        </div>

        <table class="table table-bordered">
            <thead>
                <tr><th>#</th><th>Code</th><th>Product</th><th>Type</th><th>Qty</th><th>Cost Price</th><th>Selling Price</th><th>Total</th></tr>
            </thead>
            <tbody>
                <?php $i = 1; foreach ($items_list as $item): ?>
                <tr>
                    <td><?= $i++ ?></td>
                    <td><code><?= htmlspecialchars($item['product_code']) ?></code></td>
                    <td><?= htmlspecialchars($item['product_name']) ?></td>
                    <td><?= htmlspecialchars(ucfirst($item['product_type'] ?? 'N/A')) ?></td>
                    <td class="text-center"><?= (int)$item['quantity'] ?></td>
                    <td class="text-end"><?= $currency_symbol ?> <?= number_format($item['cost_price'], 2) ?></td>
                    <td class="text-end"><?= $currency_symbol ?> <?= number_format($item['selling_price'], 2) ?></td>
                    <td class="text-end"><?= $currency_symbol ?> <?= number_format($item['total_price'], 2) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <div class="row">
            <div class="col-6">
                <p><strong>Total Items:</strong> <?= $total_qty ?></p>
            </div>
            <div class="col-6">
                <table class="table table-sm table-borderless summary-table">
                    <tr><td>Subtotal</td><td class="text-end"><?= $currency_symbol ?> <?= number_format($purchase['subtotal'], 2) ?></td></tr>
                    <tr><td>Discount</td><td class="text-end">- <?= $currency_symbol ?> <?= number_format($purchase['discount'], 2) ?></td></tr>
                    <tr><td>Tax</td><td class="text-end">+ <?= $currency_symbol ?> <?= number_format($purchase['tax'], 2) ?></td></tr>
                    <tr class="fw-bold"><td>Total Amount</td><td class="text-end"><?= $currency_symbol ?> <?= number_format($purchase['total_amount'], 2) ?></td></tr>
                    <tr><td>Paid Amount</td><td class="text-end"><?= $currency_symbol ?> <?= number_format($purchase['paid_amount'], 2) ?></td></tr>
                    <tr class="fw-bold"><td>Due Amount</td><td class="text-end"><?= $currency_symbol ?> <?= number_format($purchase['due_amount'], 2) ?></td></tr>
                </table>
            </div>
        </div>

        <div class="footer-text">
            <p class="mb-0">Generated by <?= htmlspecialchars($shop_name) ?> on <?= date('Y-m-d h:i A') ?></p>
            <p class="mb-0">This is a computer-generated document. No signature is required.</p>
        </div>
    </div>

    <script>
        window.onload = function() { setTimeout(function() { window.print(); }, 500); };
    </script>
</body>
</html>
