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

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

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role'];

$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.*,
        i.name AS item_name,
        i.model_no,
        gri.serial_number,
        (gri.received_qty * gri.rate) AS line_total
    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 = $items_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Calculate Grand Total
$grand_total = array_sum(array_column($items, 'line_total'));
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GRN #<?= str_pad($grn_id, 5, '0', STR_PAD_LEFT) ?> - View</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root {
            --primary: #a855f7;
            --accent: #c084fc;
            --glass: rgba(255,255,255,0.10);
            --glass-border: rgba(255,255,255,0.20);
        }

        * { margin:0; padding:0; box-sizing:border-box; }

        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: linear-gradient(135deg, rgba(0,0,0,0.78), rgba(0,0,0,0.92)), 
                        url('../background.jpeg') center/cover fixed;
            color: #f1f5f9;
            padding: 20px 15px;
            min-height: 100vh;
        }

        .container { max-width: 1250px; margin: auto; }

        .glass-container {
            background: var(--glass);
            backdrop-filter: blur(24px);
            border-radius: 32px;
            border: 1px solid var(--glass-border);
            box-shadow: 0 25px 80px rgba(0,0,0,0.65);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(90deg, rgba(168,85,247,0.35), rgba(147,51,234,0.25));
            padding: 50px 40px;
            text-align: center;
            position: relative;
        }
        .header h1 {
            font-size: clamp(28px, 5vw, 42px);
            font-weight: 700;
        }

        .content { padding: 40px; }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
            gap: 25px;
            margin-bottom: 40px;
        }

        .info-item label {
            display: block;
            font-size: 0.95rem;
            opacity: 0.75;
            margin-bottom: 6px;
        }

        .info-item p {
            font-size: 1.1rem;
            font-weight: 600;
        }

        .status-badge {
            padding: 8px 20px;
            border-radius: 50px;
            font-weight: 700;
            display: inline-block;
        }
        .status-Received { background: #22c55e; color: white; }

        table {
            width: 100%;
            border-collapse: collapse;
            margin: 30px 0;
            background: rgba(255,255,255,0.03);
            border-radius: 16px;
            overflow: hidden;
        }

        th {
            background: rgba(168,85,247,0.3);
            padding: 18px 16px;
            text-align: left;
            font-weight: 600;
        }

        td {
            padding: 16px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }

        tr:hover {
            background: rgba(255,255,255,0.06);
        }

        .total-row {
            background: rgba(168,85,247,0.2);
            font-weight: 700;
            font-size: 1.25rem;
        }

        .remarks-box {
            margin-top: 40px;
            padding: 25px;
            background: rgba(255,255,255,0.06);
            border-left: 5px solid var(--primary);
            border-radius: 16px;
            white-space: pre-wrap;
        }

        .action-buttons {
            margin-top: 40px;
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
        }

        .btn {
            padding: 14px 28px;
            border-radius: 16px;
            text-decoration: none;
            font-weight: 700;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            transition: all 0.3s;
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
        }

        .btn-secondary {
            background: rgba(255,255,255,0.15);
            color: white;
        }

        @media (max-width: 768px) {
            .glass-container { border-radius: 24px; }
            .header, .content { padding: 35px 25px; }
            .info-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>

<?php include '../config/header.php'; ?>

<div class="container">
    <div class="glass-container">

        <!-- Header -->
        <div class="header">
            <a href="grn_list.php" style="color:#c4b5fd; text-decoration:none; position:absolute; left:40px; top:35px; font-weight:500;">
                ← Back to GRN List
            </a>
            <h1><i class="fas fa-truck"></i> Goods Received Note</h1>
            <p style="margin-top:12px; opacity:0.9;">GRN-<?= str_pad($grn_id, 5, '0', STR_PAD_LEFT) ?></p>
        </div>

        <div class="content">

            <!-- Basic Info -->
            <div class="info-grid">
                <div class="info-item">
                    <label>GRN Date</label>
                    <p><?= date('d M Y', strtotime($grn['grn_date'])) ?></p>
                </div>
                <div class="info-item">
                    <label>Vendor</label>
                    <p><?= htmlspecialchars($grn['vendor']) ?></p>
                </div>
                <div class="info-item">
                    <label>Project</label>
                    <p>
                        <?php if ($grn['project_name']): ?>
                            <?= htmlspecialchars($grn['project_code']) ?> - <?= htmlspecialchars($grn['project_name']) ?>
                        <?php else: ?>
                            <em>Central Stock</em>
                        <?php endif; ?>
                    </p>
                </div>
                <div class="info-item">
                    <label>Status</label>
                    <p>
                        <span class="status-badge status-<?= htmlspecialchars($grn['status']) ?>">
                            <?= htmlspecialchars($grn['status']) ?>
                        </span>
                    </p>
                </div>
            </div>

            <div class="info-grid">
                <div class="info-item">
                    <label>Invoice / DC Number</label>
                    <p><?= htmlspecialchars($grn['invoice_number'] ?: '—') ?></p>
                </div>
                <div class="info-item">
                    <label>Received By</label>
                    <p><?= htmlspecialchars($grn['received_by_name'] ?? 'System') ?></p>
                </div>
            </div>

            <!-- Items Table -->
            <h3 style="margin:35px 0 15px; color:#ddd6fe;">Received Items</h3>
            <table>
                <thead>
                    <tr>
                        <th style="width:50px;">#</th>
                        <th>Model No</th>
                        <th>Serial No</th>
                        <th>Item Name</th>
                        <th>Received Qty</th>
                        <th>Unit</th>
                        <th>Rate (₹)</th>
                        <th>Batch / Lot</th>
                        <th style="text-align:right;">Line Total</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($items as $i => $item): ?>
                    <tr>
                        <td><?= $i + 1 ?></td>
                        <td><?= htmlspecialchars($item['model_no'] ?: '—') ?></td>
                        <td><?= htmlspecialchars($item['serial_number'] ?: '—') ?></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="8" style="text-align:right;">Grand Total Value</td>
                        <td style="text-align:right;">₹ <?= number_format($grand_total, 2) ?></td>
                    </tr>
                </tfoot>
            </table>

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

            <!-- Action Buttons -->
            <div class="action-buttons">
                <a href="grn_list.php" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> Back to List
                </a>
                
                <a href="grn_print.php?id=<?= $grn_id ?>" target="_blank" class="btn btn-primary">
                    <i class="fas fa-print"></i> Print GRN
                </a>

                <?php if (in_array($user_role, ['admin', 'store manager'])): ?>
                <a href="grn_edit.php?id=<?= $grn_id ?>" class="btn btn-secondary">
                    <i class="fas fa-edit"></i> Edit GRN
                </a>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

</body>
</html>

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