    <?php
session_start();
require_once("../config/config.php");

// Basic access check (allow store manager, admin, project manager)
$allowed_roles = ['store manager', 'admin', 'project manager'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], $allowed_roles)) {
    header("Location: ../login.php");
    exit();
}

$grn_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($grn_id <= 0) {
    die("<h2 style='color:#ef4444;text-align:center;padding:100px;'>Invalid GRN ID</h2>");
}

// Fetch GRN header
$grn_query = "
    SELECT 
        grn.*,
        p.project_code, p.project_name,
        u.full_name AS received_by_name
    FROM goods_received_note grn
    LEFT JOIN project_master p ON grn.project_id = p.id
    LEFT JOIN users u ON grn.received_by = u.id
    WHERE grn.id = ?
";
$grn_stmt = $conn->prepare($grn_query);
$grn_stmt->bind_param("i", $grn_id);
$grn_stmt->execute();
$grn = $grn_stmt->get_result()->fetch_assoc();

if (!$grn) {
    die("<h2 style='color:#ef4444;text-align:center;padding:100px;'>GRN not found</h2>");
}

// Fetch GRN items
$items_query = "
    SELECT 
        gri.received_qty, gri.rate, gri.batch_no, gri.unit,
        (gri.received_qty * gri.rate) AS line_total,
        i.name AS item_name
    FROM goods_received_note_items gri
    INNER JOIN inventory_master i ON gri.item_id = i.id
    WHERE gri.grn_id = ?
    ORDER BY i.name ASC
";
$items_stmt = $conn->prepare($items_query);
$items_stmt->bind_param("i", $grn_id);
$items_stmt->execute();
$items_result = $items_stmt->get_result();

// Calculate grand total
$grand_total = 0;
$items = [];
while ($item = $items_result->fetch_assoc()) {
    $grand_total += $item['line_total'];
    $items[] = $item;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GRN Print - <?= str_pad($grn_id, 5, '0', STR_PAD_LEFT) ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        body {
            font-family: 'Arial', 'Helvetica', sans-serif;
            margin: 0;
            padding: 0;
            background: #fff;
            color: #000;
            font-size: 12pt;
        }
        .print-container {
            width: 210mm; /* A4 width */
            min-height: 297mm; /* A4 height */
            margin: 0 auto;
            padding: 20mm 15mm;
            box-sizing: border-box;
        }
        .header {
            text-align: center;
            margin-bottom: 20px;
            border-bottom: 2px solid #000;
            padding-bottom: 10px;
        }
        .header h1 {
            margin: 0;
            font-size: 18pt;
            font-weight: bold;
        }
        .grn-no {
            font-size: 14pt;
            margin: 10px 0;
        }
        .info-table {
            width: 100%;
            margin-bottom: 20px;
        }
        .info-table td {
            padding: 6px 0;
            vertical-align: top;
        }
        .info-label {
            font-weight: bold;
            width: 160px;
        }
        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        .items-table th, .items-table td {
            border: 1px solid #000;
            padding: 8px;
            text-align: left;
        }
        .items-table th {
            background: #f0f0f0;
            font-weight: bold;
        }
        .total-row {
            font-weight: bold;
            background: #f8f8f8;
        }
        .sign-section {
            margin-top: 60px;
            display: flex;
            justify-content: space-between;
        }
        .sign-box {
            width: 45%;
            text-align: center;
            border-top: 1px solid #000;
            padding-top: 40px;
        }

        /* Print-specific styles */
        @media print {
            .no-print { display: none !important; }
            body { background: white !important; }
            .print-container { padding: 0; margin: 0; width: 100%; }
        }
    </style>
</head>
<body>

<div class="print-container">
    <div class="header">
        <h1>GOODS RECEIVED NOTE</h1>
        <div class="grn-no">GRN No: <?= str_pad($grn_id, 5, '0', STR_PAD_LEFT) ?></div>
    </div>

    <table class="info-table">
        <tr>
            <td class="info-label">Date:</td>
            <td><?= date('d-m-Y', strtotime($grn['grn_date'])) ?></td>
            <td class="info-label">PO No:</td>
            <td><?= htmlspecialchars($grn['po_number'] ?: '—') ?></td>
        </tr>
        <tr>
            <td class="info-label">Vendor:</td>
            <td><?= htmlspecialchars($grn['vendor']) ?></td>
            <td class="info-label">Invoice No:</td>
            <td><?= htmlspecialchars($grn['invoice_number'] ?: '—') ?></td>
        </tr>
        <tr>
            <td class="info-label">Project:</td>
            <td colspan="3">
                <?= $grn['project_name'] ? htmlspecialchars($grn['project_name']) . ' (' . htmlspecialchars($grn['project_code']) . ')' : 'Central Stock / General Receipt' ?>
            </td>
        </tr>
        <tr>
            <td class="info-label">Received By:</td>
            <td colspan="3"><?= htmlspecialchars($grn['received_by_name'] ?? '—') ?></td>
        </tr>
    </table>

    <div style="margin: 20px 0; font-weight: bold; font-size: 14pt;">Received Items</div>

    <table class="items-table">
        <thead>
            <tr>
                <th>#</th>
                <th>Item Name</th>
                <th>Qty Received</th>
                <th>Unit</th>
                <th>Rate (₹)</th>
                <th>Batch/Lot</th>
                <th>Amount (₹)</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $counter = 1;
            foreach ($items as $item): ?>
                <tr>
                    <td><?= $counter++ ?></td>
                    <td><?= htmlspecialchars($item['item_name']) ?></td>
                    <td><?= number_format($item['received_qty'], 3) ?></td>
                    <td><?= htmlspecialchars($item['unit']) ?></td>
                    <td><?= number_format($item['rate'], 2) ?></td>
                    <td><?= htmlspecialchars($item['batch_no'] ?: '—') ?></td>
                    <td style="text-align:right;"><?= number_format($item['line_total'], 2) ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
        <tfoot>
            <tr class="total-row">
                <td colspan="6" style="text-align:right;">Grand Total:</td>
                <td style="text-align:right;">₹ <?= number_format($grand_total, 2) ?></td>
            </tr>
        </tfoot>
    </table>

    <?php if (!empty($grn['remarks'])): ?>
        <div style="margin-top: 30px;">
            <strong>Remarks / Notes:</strong><br>
            <?= nl2br(htmlspecialchars($grn['remarks'])) ?>
        </div>
    <?php endif; ?>

    <div class="sign-section">
        <div class="sign-box">
            Prepared By<br>
            <?= htmlspecialchars($full_name) ?><br>
            <?= ucfirst($user_role) ?><br>
            Date: <?= date('d-m-Y') ?>
        </div>
        <div class="sign-box">
            Received By<br>
            ________________________<br>
            Name & Signature<br>
            Date: __________
        </div>
    </div>

    <!-- Print button - only visible on screen -->
    <div class="no-print" style="text-align:center; margin-top:40px;">
        <button onclick="window.print()" style="padding:12px 30px; font-size:1.1rem; background:#8b5cf6; color:white; border:none; border-radius:8px; cursor:pointer;">
            <i class="fas fa-print"></i> Print GRN
        </button>
    </div>
</div>

</body>
</html>

<?php
$grn_stmt->close();
$items_stmt->close();
$conn->close();
?>