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

// Optional filters
$project_id = isset($_GET['project_id']) ? (int)$_GET['project_id'] : 0;

// Build Query
$where = " WHERE 1=1";
$params = [];
$types = "";

if ($project_id > 0) {
    $where .= " AND po.project_id = ?";
    $params[] = $project_id;
    $types .= "i";
}

$query = "
    SELECT 
        po.id,
        po.po_date,
        po.vendor,
        po.status,
        po.basic_total,
        po.total_gst,
        po.grand_total,
        p.project_code,
        p.project_name,
        COUNT(poi.id) AS item_count
    FROM purchase_order po
    LEFT JOIN project_master p ON po.project_id = p.id
    LEFT JOIN purchase_order_items poi ON po.id = poi.po_id
    $where
    GROUP BY po.id
    ORDER BY po.po_date DESC, po.id DESC
    LIMIT 100
";

$stmt = $conn->prepare($query);
if ($types) $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>Purchase Orders</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: 1450px; 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-box {
            flex: 1;
            min-width: 280px;
        }
        .search-box input {
            width: 100%;
            padding: 14px 20px;
            background: rgba(255,255,255,0.09);
            border: 1px solid rgba(255,255,255,0.25);
            border-radius: 16px;
            color: white;
            font-size: 16px;
        }

        .add-btn {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            padding: 14px 28px;
            border-radius: 16px;
            text-decoration: none;
            font-weight: 700;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            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;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        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-Issued { background: #22c55e; color: white; }

        .action-btns a {
            padding: 9px 13px;
            border-radius: 10px;
            margin: 0 4px;
            text-decoration: none;
            font-size: 1rem;
            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; }

        .po-number {
            font-weight: 700;
            color: #c4b5fd;
        }

        .no-records {
            text-align: center;
            padding: 100px 20px;
            color: #94a3b8;
        }
        .no-records i {
            font-size: 5rem;
            opacity: 0.3;
            margin-bottom: 20px;
        }

        @media (max-width: 768px) {
            .top-bar { flex-direction: column; align-items: stretch; }
            th, td { padding: 14px 10px; font-size: 0.95rem; }
            .glass-container { border-radius: 24px; }
            .header, .top-bar, .table-container { padding-left: 20px; padding-right: 20px; }
        }
    </style>
</head>
<body>

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

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

        <!-- Header -->
        <div class="header">
            <a href="../admin/dashboard_admin.php" style="color:#c4b5fd; text-decoration:none; position:absolute; left:40px; top:35px; font-weight:500;">
                ← Back to Purchase Management
            </a>
            <h1><i class="fas fa-receipt"></i> Purchase Orders</h1>
            <p style="margin-top:12px; opacity:0.9;">Manage all purchase orders</p>
        </div>

        <!-- Top Bar -->
        <div class="top-bar">
            <div class="search-box">
                <input type="text" id="searchInput" placeholder="Search by PO number, vendor, or project..." onkeyup="filterTable()">
            </div>
            <a href="po_create.php" class="add-btn">
                <i class="fas fa-plus"></i> New Purchase Order
            </a>
        </div>

        <!-- Table -->
        <div class="table-container">
            <?php if ($result->num_rows > 0): ?>
                <table id="poTable">
                    <thead>
                        <tr>
                            <th>PO Date</th>
                            <th>PO Number</th>
                            <th>Vendor</th>
                            <th>Project</th>
                            <th>Items</th>
                            <th>Basic Total</th>
                            <th>GST</th>
                            <th>Grand Total</th>
                            <th>Status</th>
                            <th style="text-align:center; width:160px;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php while ($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td><?= date('d M Y', strtotime($row['po_date'])) ?></td>
                            <td class="po-number">PO-<?= str_pad($row['id'], 5, '0', STR_PAD_LEFT) ?></td>
                            <td><?= htmlspecialchars($row['vendor']) ?></td>
                            <td>
                                <?php if ($row['project_code']): ?>
                                    <strong><?= htmlspecialchars($row['project_code']) ?></strong><br>
                                    <small><?= htmlspecialchars($row['project_name']) ?></small>
                                <?php else: ?>
                                    <em>Central Purchase</em>
                                <?php endif; ?>
                            </td>
                            <td><strong><?= $row['item_count'] ?></strong></td>
                            <td>₹ <?= number_format($row['basic_total'], 2) ?></td>
                            <td>₹ <?= number_format($row['total_gst'], 2) ?></td>
                            <td><strong>₹ <?= number_format($row['grand_total'], 2) ?></strong></td>
                            <td>
                                <span class="status status-Issued"><?= htmlspecialchars($row['status']) ?></span>
                            </td>
                            <td class="action-btns" style="text-align:center; white-space:nowrap;">
                                <a href="po_view.php?id=<?= $row['id'] ?>" class="btn-view" title="View">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <a href="po_edit.php?id=<?= $row['id'] ?>" class="btn-edit" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="po_print.php?id=<?= $row['id'] ?>" class="btn-print" target="_blank" title="Print">
                                    <i class="fas fa-print"></i>
                                </a>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="no-records">
                    <i class="fas fa-receipt"></i>
                    <h2>No Purchase Orders Found</h2>
                    <p>Start by creating a new Purchase Order.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
function filterTable() {
    const input = document.getElementById("searchInput").value.toLowerCase();
    const rows = document.querySelectorAll("#poTable tbody tr");

    rows.forEach(row => {
        row.style.display = row.textContent.toLowerCase().includes(input) ? "" : "none";
    });
}
</script>

</body>
</html>

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