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

$pdo = getDB();

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

$stmt = $pdo->prepare("
    SELECT g.*, s.supplier_name, s.phone as supplier_phone, s.address as supplier_address,
           u.name as created_by_name, r.name as received_by_name
    FROM grns g
    LEFT JOIN suppliers s ON g.supplier_id = s.id
    LEFT JOIN users u ON g.created_by = u.id
    LEFT JOIN users r ON g.received_by = r.id
    WHERE g.id = ?
");
$stmt->execute([$id]);
$grn = $stmt->fetch();
if (!$grn) { die('GRN not found.'); }

$stmt = $pdo->prepare("
    SELECT gi.*, p.product_name, p.product_type, p.product_code
    FROM grn_items gi
    JOIN products p ON gi.product_id = p.id
    WHERE gi.grn_id = ?
");
$stmt->execute([$id]);
$items = $stmt->fetchAll();

foreach ($items as &$item) {
    if ($item['product_type'] === 'phone') {
        $stmt = $pdo->prepare("SELECT imei_number FROM grn_item_imeis WHERE grn_item_id = ?");
        $stmt->execute([$item['id']]);
        $item['imeis'] = $stmt->fetchAll();
    }
}
unset($item);

$shop_name = getSetting('shop_name', 'DigiMobiz');
$shop_address = getSetting('shop_address', '');
$shop_phone = getSetting('shop_phone', '');
$shop_email = getSetting('shop_email', '');
$currency = getSetting('currency_symbol', 'Rs.');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>GRN - <?= htmlspecialchars($grn['grn_no']) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { font-family: 'Segoe UI', Arial, sans-serif; background: #fff; padding: 20px; font-size: 0.9rem; }
        .grn-box { max-width: 800px; margin: auto; padding: 20px; border: 1px solid #eee; border-radius: 8px; }
        .header { text-align: center; margin-bottom: 20px; border-bottom: 2px solid #1a237e; padding-bottom: 15px; }
        .header img { max-height: 60px; }
        .header h3 { color: #1a237e; font-weight: 700; }
        .header p { margin-bottom: 0; color: #666; }
        .title { text-align: center; font-size: 1.3rem; font-weight: 700; color: #1a237e; margin: 15px 0; }
        table.items { width: 100%; border-collapse: collapse; margin: 10px 0; }
        table.items th { background: #1a237e; color: #fff; padding: 8px; text-align: left; font-size: 0.85rem; }
        table.items td { padding: 6px 8px; border-bottom: 1px solid #ddd; }
        table.items tr:nth-child(even) { background: #f8f9fa; }
        .total-table { width: 100%; max-width: 350px; margin-left: auto; }
        .total-table td { padding: 4px 8px; }
        .btn-print { text-align: center; margin: 20px 0; }
        @media print {
            .btn-print { display: none; }
            body { padding: 0; }
            .grn-box { border: none; padding: 0; }
        }
    </style>
</head>
<body>
    <div class="btn-print">
        <button class="btn btn-primary" onclick="window.print()"><i class="fas fa-print me-1"></i> Print</button>
        <a href="view_grn.php?id=<?= $id ?>" class="btn btn-secondary"><i class="fas fa-arrow-left me-1"></i> Back</a>
    </div>

    <div class="grn-box">
        <div class="header">
            <img src="<?= htmlspecialchars(getShopLogoUrl()) ?>?v=<?= time() ?>" alt="Logo" onerror="this.style.display='none'">
            <h3><?= htmlspecialchars($shop_name) ?></h3>
            <p><?= nl2br(htmlspecialchars($shop_address)) ?></p>
            <p>Phone: <?= htmlspecialchars($shop_phone) ?><?= $shop_email ? ' | Email: ' . htmlspecialchars($shop_email) : '' ?></p>
        </div>

        <div class="title">GOODS RECEIVED NOTE</div>

        <div class="row mb-3">
            <div class="col-6">
                <strong>GRN No:</strong> <?= htmlspecialchars($grn['grn_no']) ?><br>
                <strong>Date:</strong> <?= formatDate($grn['received_date']) ?><br>
                <strong>Supplier Invoice:</strong> <?= htmlspecialchars($grn['supplier_invoice_no'] ?? '-') ?><br>
                <strong>PO No:</strong> <?= htmlspecialchars($grn['purchase_order_no'] ?? '-') ?>
            </div>
            <div class="col-6 text-end">
                <strong>Supplier:</strong><br>
                <?= htmlspecialchars($grn['supplier_name'] ?? '-') ?><br>
                <?= htmlspecialchars($grn['supplier_phone'] ?? '') ?><br>
                <?= nl2br(htmlspecialchars($grn['supplier_address'] ?? '')) ?>
            </div>
        </div>

        <table class="items">
            <thead><tr><th>#</th><th>Product</th><th>Code</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 as $item): ?>
                <tr>
                    <td><?= $i++ ?></td>
                    <td><?= htmlspecialchars($item['product_name']) ?></td>
                    <td><?= htmlspecialchars($item['product_code']) ?></td>
                    <td><?= ucfirst($item['product_type']) ?></td>
                    <td><?= $item['quantity'] ?></td>
                    <td><?= $currency ?> <?= number_format($item['cost_price'], 2) ?></td>
                    <td><?= $currency ?> <?= number_format($item['selling_price'], 2) ?></td>
                    <td><?= $currency ?> <?= number_format($item['total_price'], 2) ?></td>
                </tr>
                <?php if (!empty($item['imeis'])): ?>
                <tr>
                    <td colspan="8" style="padding-left:40px;">
                        <strong>IMEI:</strong>
                        <?php foreach ($item['imeis'] as $imei): ?>
                        <code><?= htmlspecialchars($imei['imei_number']) ?></code>
                        <?php endforeach; ?>
                    </td>
                </tr>
                <?php endif; ?>
                <?php endforeach; ?>
            </tbody>
        </table>

        <table class="total-table">
            <tr><td>Subtotal:</td><td class="text-end"><?= formatCurrency($grn['subtotal']) ?></td></tr>
            <?php if ($grn['discount'] > 0): ?>
            <tr><td>Discount:</td><td class="text-end">-<?= formatCurrency($grn['discount']) ?></td></tr>
            <?php endif; ?>
            <?php if ($grn['tax'] > 0): ?>
            <tr><td>Tax:</td><td class="text-end"><?= formatCurrency($grn['tax']) ?></td></tr>
            <?php endif; ?>
            <tr style="font-weight:700;border-top:2px solid #1a237e;"><td>Total Amount:</td><td class="text-end"><?= formatCurrency($grn['total_amount']) ?></td></tr>
        </table>

        <p style="margin-top:30px;"><strong>Received By:</strong> _________________________</p>
        <p style="margin-top:5px;"><?= htmlspecialchars($grn['received_by_name'] ?? '') ?></p>

        <p style="margin-top:30px;font-size:0.85rem;color:#666;" class="text-center">This is a computer-generated document. No signature required.</p>
    </div>

    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
