<?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'];
$full_name = $_SESSION['full_name'] ?? 'Project Manager';

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

// Build Query
$where = "WHERE pr.requested_by = ?";
$params = [$user_id];
$types = "i";

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

$query = "
    SELECT 
        pr.id,
        pr.pr_date,
        pr.required_by_date,
        pr.status,
        pr.remarks,
        p.project_code,
        p.project_name,
        COUNT(pri.id) AS item_count,
        COALESCE(SUM(pri.requested_qty), 0) AS total_qty
    FROM procurement_request pr
    INNER JOIN project_master p ON pr.project_id = p.id
    LEFT JOIN procurement_request_items pri ON pr.id = pri.pr_id
    $where
    GROUP BY pr.id
    ORDER BY pr.pr_date DESC, pr.id DESC
";

$stmt = $conn->prepare($query);
$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>My Procurement Requests</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;
        }
        .search-box input {
            width: 100%;
            padding: 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;
        }

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

        .status-badge {
            padding: 6px 16px;
            border-radius: 30px;
            font-size: 0.9rem;
            font-weight: 600;
        }
        .status-Pending   { background: rgba(245,158,11,0.25); color: #fcd34d; }
        .status-Approved  { background: rgba(34,197,94,0.25); color: #86efac; }
        .status-Rejected  { background: rgba(239,68,68,0.25); color: #fca5a5; }
        .status-Processed { background: rgba(59,130,246,0.25); color: #93c5fd; }

        .no-records {
            text-align: center;
            padding: 100px 20px;
            opacity: 0.7;
        }
        .no-records 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_id > 0 ? "../project/project_dashboard.php?id=$project_id" : "dashboard_project_manager.php" ?>" 
               style="color:#c4b5fd; text-decoration:none; float:left; font-size:1.1rem;">
                ← Back
            </a>
            <h1><i class="fas fa-file-import"></i> My Procurement Requests</h1>
            <p style="margin-top:8px; opacity:0.9;">
                <?= $project_id > 0 ? htmlspecialchars($project['project_name'] ?? '') : 'All Projects' ?> 
                • <?= htmlspecialchars($full_name) ?>
            </p>
        </div>

        <div class="form-area">
            <!-- Search -->
            <div class="search-box">
                <input type="text" id="searchInput" placeholder="Search by Project or PR Number..." onkeyup="filterTable()">
            </div>

            <?php if ($result->num_rows > 0): ?>
                <table id="prTable">
                    <thead>
                        <tr>
                            <th>PR Date</th>
                            <th>Project</th>
                            <th>Required By</th>
                            <th>Items</th>
                            <th>Total Qty</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($row = $result->fetch_assoc()): ?>
                            <tr>
                                <td><?= date('d M Y', strtotime($row['pr_date'])) ?></td>
                                <td>
                                    <strong><?= htmlspecialchars($row['project_code']) ?></strong><br>
                                    <small><?= htmlspecialchars($row['project_name']) ?></small>
                                </td>
                                <td><?= $row['required_by_date'] ? date('d M Y', strtotime($row['required_by_date'])) : '—' ?></td>
                                <td><?= $row['item_count'] ?></td>
                                <td><?= number_format($row['total_qty'], 2) ?></td>
                                <td>
                                    <span class="status-badge status-<?= htmlspecialchars($row['status']) ?>">
                                        <?= htmlspecialchars($row['status']) ?>
                                    </span>
                                </td>
                                <td>
                                    <a href="pr_view.php?pr_id=<?= $row['id'] ?>" style="color:var(--accent); margin-right:12px;">
                                        <i class="fas fa-eye"></i> View
                                    </a>
                                    <?php if ($row['status'] === 'Pending'): ?>
                                        <a href="pr_edit.php?pr_id=<?= $row['id'] ?>" style="color:#f59e0b;">
                                            <i class="fas fa-edit"></i> Edit
                                        </a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="no-records">
                    <i class="fas fa-file-import"></i>
                    <h2>No Procurement Requests Found</h2>
                    <p>Start by raising a new PR for your project.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
// Live Search
function filterTable() {
    const input = document.getElementById("searchInput").value.toUpperCase();
    const table = document.getElementById("prTable");
    if (!table) return;
    
    const tr = table.getElementsByTagName("tr");

    for (let i = 1; i < tr.length; i++) {
        const projectTd = tr[i].getElementsByTagName("td")[1];
        if (projectTd) {
            const text = projectTd.textContent || projectTd.innerText;
            tr[i].style.display = text.toUpperCase().indexOf(input) > -1 ? "" : "none";
        }
    }
}
</script>

</body>
</html>

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