<?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();
}

// Search & Filter
$search = trim($_GET['search'] ?? '');
$status = $_GET['status'] ?? '';
$project_id = $_GET['project_id'] ?? '';
// Build query
$sql = "SELECT g.*, p.project_name, u.full_name AS received_by_name 
        FROM goods_received_note g 
        LEFT JOIN project_master p ON g.project_id = p.id 
        LEFT JOIN users u ON g.received_by = u.id 
        WHERE 1=1";

$params = [];
$types = "";

if (!empty($search)) {
    $sql .= " AND (g.grn_code LIKE ? OR g.vendor LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $types .= "ss";
}

if (!empty($status)) {
    $sql .= " AND g.status = ?";
    $params[] = $status;
    $types .= "s";
}

$sql .= " ORDER BY g.created_at DESC";

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Goods Received Notes (GRN)</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: 1350px; 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;
        }

        .top-bar {
            padding: 25px 40px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
            background: rgba(255,255,255,0.05);
        }

        .search-form {
            display: flex;
            gap: 12px;
            flex: 1;
            flex-wrap: wrap;
        }

        .search-form input,
        .search-form select {
            padding: 14px 18px;
            background: rgba(255,255,255,0.09);
            border: 1px solid rgba(255,255,255,0.25);
            border-radius: 16px;
            color: white;
            font-size: 16px;
        }

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

        .btn-primary {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            box-shadow: 0 10px 25px rgba(168,85,247,0.4);
        }

        .table-container { padding: 0 40px 40px; }

        table {
            width: 100%;
            border-collapse: collapse;
        }

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

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

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

        .status {
            padding: 8px 18px;
            border-radius: 50px;
            font-size: 0.9rem;
            font-weight: 700;
        }
        .status-Received { background: #22c55e; color: white; }
        .status-Pending  { background: #f59e0b; color: white; }

        .action-btns a {
            padding: 9px 13px;
            border-radius: 10px;
            margin: 0 4px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }
        .btn-view  { background: rgba(59,130,246,0.25); color: #60a5fa; }
        .btn-edit  { background: rgba(234,179,8,0.25); color: #fde047; }
        .btn-print { background: rgba(34,197,94,0.25); color: #4ade80; }
        .no-records {
            text-align: center;
            padding: 100px 20px;
            color: #94a3b8;
        }

        @media (max-width: 768px) {
            .glass-container { border-radius: 24px; }
            .header, .top-bar, .table-container { padding-left: 20px; padding-right: 20px; }
            .search-form { flex-direction: column; }
        }
    </style>
</head>
<body>

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

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

        <!-- Header -->
        <div class="header">
            <h1><i class="fas fa-truck"></i> Goods Received Notes (GRN)</h1>
            <p style="margin-top:12px; opacity:0.9;">Track all incoming material receipts</p>
        </div>

        <!-- Top Bar -->
        <div class="top-bar">
            <form method="GET" class="search-form">
                <input type="text" name="search" placeholder="Search GRN Code or Vendor..." 
                       value="<?= htmlspecialchars($search) ?>" style="flex:1; min-width:280px;">

                <select name="status" style="min-width:180px;">
                    <option value="">All Status</option>
                    <option value="Received" <?= $status === 'Received' ? 'selected' : '' ?>>Received</option>
                    <option value="Pending" <?= $status === 'Pending' ? 'selected' : '' ?>>Pending</option>
                </select>

                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-search"></i> Search
                </button>

                <a href="grn_list.php" class="btn" style="background:rgba(255,255,255,0.1); color:white;">
                    Clear
                </a>
            </form>

            <a href="grn_add.php?project_id=<?= $project_id ?>" class="btn btn-primary">
                <i class="fas fa-plus"></i> Create New GRN
            </a>
        </div>

        <!-- Success Message -->
        <?php if (isset($_GET['success'])): ?>
            <div style="margin:20px 40px; padding:16px 24px; background:rgba(34,197,94,0.25); border:1px solid #4ade80; color:#86efac; border-radius:16px; font-weight:600;">
                GRN created successfully!
            </div>
        <?php endif; ?>

        <!-- Table -->
        <div class="table-container">
            <?php if ($result->num_rows > 0): ?>
                <table>
                    <thead>
                        <tr>
                            <th>GRN Code</th>
                            <th>GRN Date</th>
                            <th>Vendor</th>
                            <th>Project</th>
                            <th>Invoice No</th>
                            <th>Status</th>
                            <th>Received By</th>
                            <th>Created At</th>
                            <th style="text-align:center; width:100px;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td><strong><?= htmlspecialchars($row['grn_code'] ?? 'GRN-'.str_pad($row['id'],5,'0',STR_PAD_LEFT)) ?></strong></td>
                            <td><?= date('d M Y', strtotime($row['grn_date'])) ?></td>
                            <td><?= htmlspecialchars($row['vendor']) ?></td>
                            <td><?= htmlspecialchars($row['project_name'] ?? 'Central Stock') ?></td>
                            <td><?= htmlspecialchars($row['invoice_number'] ?? '-') ?></td>
                            <td>
                                <span class="status status-<?= htmlspecialchars($row['status']) ?>">
                                    <?= htmlspecialchars($row['status']) ?>
                                </span>
                            </td>
                            <td><?= htmlspecialchars($row['received_by_name'] ?? 'Unknown') ?></td>
                            <td><?= date('d M Y H:i', strtotime($row['created_at'])) ?></td>
                            <td class="action-btns" style="text-align:center;">
                                <a href="grn_view.php?id=<?= $row['id'] ?>" class="action-btns btn-view" title="View">
                                    <i class="fas fa-eye"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="no-records">
                    <i class="fas fa-truck" style="font-size:5rem; opacity:0.3; margin-bottom:20px;"></i>
                    <h3>No GRN Records Found</h3>
                    <p>Start by creating your first Goods Received Note.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

</body>
</html>

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