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

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

$user_id = $_SESSION['user_id'];
$project_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($project_id <= 0) {
    die("<h2 style='color:#ef4444;text-align:center;padding:100px;'>Invalid Project ID</h2>");
}

// Verify Project Access
$check = $conn->prepare("
    SELECT p.project_code, p.project_name 
    FROM project_master p
    LEFT JOIN project_managers pm ON p.id = pm.project_id
    WHERE p.id = ? AND pm.user_id = ?
");
$check->bind_param("ii", $project_id, $user_id);
$check->execute();
$project = $check->get_result()->fetch_assoc();

if (!$project) {
    die("<h2 style='color:#ef4444;text-align:center;padding:100px;'>Project Not Found or Access Denied</h2>");
}

// Fetch Inventory
$inventory_query = "
    SELECT 
        i.id AS item_id,
        i.name AS item_name,
        i.model_no,
        i.uom AS unit,

        pi.current_stock,
        pi.avg_rate,
        (pi.current_stock * pi.avg_rate) AS total_value,
        pi.last_updated,

        COUNT(ps.id) AS serial_count

    FROM project_inventory pi
    INNER JOIN inventory_master i ON pi.item_id = i.id

    LEFT JOIN project_inventory_serials ps 
        ON ps.item_id = i.id 
        AND ps.project_id = pi.project_id
        AND ps.status = 'IN'

    WHERE pi.project_id = ?
    GROUP BY i.id

    ORDER BY i.name ASC
";
$inv_stmt = $conn->prepare($inventory_query);
$inv_stmt->bind_param("i", $project_id);
$inv_stmt->execute();
$inventory_result = $inv_stmt->get_result();

$total_stock_value = 0;
$items = [];
while ($row = $inventory_result->fetch_assoc()) {
    $total_stock_value += $row['total_value'];
    $items[] = $row;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Project Inventory - <?= htmlspecialchars($project['project_name']) ?></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;
        }
        .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: 45px 40px;
            text-align: center;
        }
        .header h1 { font-size: 2.5rem; font-weight: 700; }

        .form-area { padding: 40px; }

        .search-box {
            width: 100%;
            max-width: 500px;
            margin: 0 auto 30px;
            position: relative;
        }
        .search-box input {
            width: 100%;
            padding: 16px 50px 16px 20px;
            background: rgba(255,255,255,0.09);
            border: 1px solid rgba(255,255,255,0.25);
            border-radius: 50px;
            color: white;
            font-size: 16px;
        }
        .search-box i {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--accent);
        }

        .summary-card {
            background: rgba(255,255,255,0.08);
            border: 1px solid rgba(255,255,255,0.18);
            border-radius: 20px;
            padding: 32px;
            text-align: center;
            margin-bottom: 35px;
        }
        .total-value {
            font-size: 3rem;
            font-weight: 800;
            color: #c4b5fd;
            margin: 12px 0;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background: rgba(0,0,0,0.25);
            border-radius: 16px;
            overflow: hidden;
        }
        th {
            background: rgba(168,85,247,0.3);
            padding: 18px 16px;
            text-align: left;
        }
        td {
            padding: 16px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        tr:hover {
            background: rgba(168,85,247,0.1);
        }
        .low-stock td:nth-child(5) {
            color: #fca5a5;
            font-weight: 700;
        }

        .no-data {
            text-align: center;
            padding: 100px 20px;
            opacity: 0.7;
        }
        .no-data i { font-size: 4.5rem; margin-bottom: 20px; opacity: 0.4; }

        @media (max-width: 768px) {
            .header h1 { font-size: 2rem; }
            table { font-size: 0.95rem; }
        }
    </style>
</head>
<body>
<?php include '../config/header.php'; ?>
<div class="container">
    <div class="glass-container">
        <div class="header">
            <a href="../project/project_dashboard.php?id=<?= $project_id ?>" style="color:#c4b5fd; text-decoration:none; float:left; font-size:1.1rem;">
                ← Back to Dashboard
            </a>
            <h1><i class="fas fa-warehouse"></i> Project Inventory</h1>
            <p style="margin-top:8px; opacity:0.9;">
                <?= htmlspecialchars($project['project_code']) ?> - <?= htmlspecialchars($project['project_name']) ?>
            </p>
        </div>

        <div class="form-area">
            <!-- Search -->
            <div class="search-box">
                <input type="text" id="searchInput" placeholder="Search by Model No or Item Name..." onkeyup="filterTable()">
                <i class="fas fa-search"></i>
            </div>

            <!-- Summary -->
            <div class="summary-card">
                <div style="font-size:1.1rem; opacity:0.85;">Total Stock Value</div>
                <div class="total-value">₹ <?= number_format($total_stock_value, 2) ?></div>
            </div>

            <!-- Table -->
            <?php if (!empty($items)): ?>
                <table id="inventoryTable">
                    <thead>
                        <tr>
                            <th>Sr. No</th>
                            <th>Model No</th>
                            
                            <th>Item Name</th>
                            <th>Unit</th>
                            <th>Current Stock</th>
                            <th>Avg. Rate (₹)</th>
                            <th>Total Value (₹)</th>
                            <th>Serials</th>
                            <th>Last Updated</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $count = 1; 
                        foreach ($items as $item): 
                            $is_low = $item['current_stock'] < 10;
                        ?>
                            <tr class="<?= $is_low ? 'low-stock' : '' ?>">
                                <td><?= $count++ ?></td>
                                <td><?= htmlspecialchars($item['model_no'] ?: '—') ?></td>
                                <td><strong><?= htmlspecialchars($item['item_name']) ?></strong></td>
                                <td><?= htmlspecialchars($item['unit'] ?: '—') ?></td>
                                <td>
                                    <?= number_format($item['current_stock'], 3) ?>

                                        <?php if ($item['serial_count'] > 0): ?>
                                        <br><small style="color:#c4b5fd;">
                                            Serial: <?= $item['serial_count'] ?>
                                        </small>
                                        <?php endif; ?>

                                        <?php if ($is_low): ?>
                                        <span style="color:#fca5a5; font-size:0.85rem;">(Low)</span>
                                    <?php endif; ?>
                                </td>
                                <td>₹ <?= number_format($item['avg_rate'], 2) ?></td>
                                <td>₹ <?= number_format($item['total_value'], 2) ?></td>
                                <td>
                                    <?php if ($item['serial_count'] > 0): ?>
                                        <button onclick="viewSerials(<?= $item['item_id'] ?>)" 
                                            style="padding:6px 12px; border:none; border-radius:8px; background:#a855f7; color:white; cursor:pointer;">
                                                View Serials
                                        </button>
                                    <?php else: ?>
                                    —
                                    <?php endif; ?>
                                </td>
                                <td><?= $item['last_updated'] ? date('d M Y h:i A', strtotime($item['last_updated'])) : '—' ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="no-data">
                    <i class="fas fa-box-open"></i>
                    <h2>No Items in Inventory Yet</h2>
                    <p>Stock will appear here once materials are received via GRN.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
// Live Search by Model No or Item Name
function filterTable() {
    const input = document.getElementById("searchInput").value.toUpperCase();
    const table = document.getElementById("inventoryTable");
    const tr = table.getElementsByTagName("tr");

    for (let i = 1; i < tr.length; i++) {
        const modelTd = tr[i].getElementsByTagName("td")[1];
        const nameTd = tr[i].getElementsByTagName("td")[2];
        
        if (modelTd || nameTd) {
            const modelText = modelTd ? modelTd.textContent || modelTd.innerText : "";
            const nameText = nameTd ? nameTd.textContent || nameTd.innerText : "";
            
            if (modelText.toUpperCase().indexOf(input) > -1 || nameText.toUpperCase().indexOf(input) > -1) {
                tr[i].style.display = "";
            } else {
                tr[i].style.display = "none";
            }
        }
    }
}
function viewSerials(item_id) {
    fetch(`get_project_serials.php?project_id=<?= $project_id ?>&item_id=` + item_id)
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                alert("Serials:\n\n" + data.serials.join("\n"));
            } else {
                alert("No serials found");
            }
        });
}
</script>

</body>
</html>

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