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

// Allowed roles: store manager, admin (adjust as needed)
// $allowed_roles = ['store manager', 'admin'];
// 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'];
$full_name = $_SESSION['full_name'] ?? 'Store/Admin';

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

// Build WHERE clause
$where = "WHERE pr.status = 'Approved'";
$params = [];
$types = "";

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

// Fetch approved PRs that are NOT yet converted to PO
$query = "
    SELECT 
        pr.id, pr.pr_date, pr.required_by_date, 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
    LEFT JOIN project_master p ON pr.project_id = p.id
    LEFT JOIN procurement_request_items pri ON pr.id = pri.pr_id
    $where
    AND NOT EXISTS (SELECT 1 FROM purchase_order WHERE pr_id = pr.id)
    GROUP BY pr.id
    ORDER BY pr.pr_date DESC, pr.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>Approved Procurement Requests (Ready for PO)</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root {
            --primary: #8b5cf6;
            --success: #22c55e;
            --warning: #f59e0b;
            --danger: #ef4444;
            --glass: rgba(255,255,255,0.07);
            --border: rgba(255,255,255,0.14);
        }
        body {
            font-family: 'Segoe UI', system-ui, sans-serif;
            background: linear-gradient(rgba(0,0,0,0.8), rgba(0,0,0,0.95)),
                        url('../background.jpeg') center/cover fixed;
            color: white;
            margin: 0;
            padding: 20px 15px;
        }
        .container { max-width: 1200px; margin: 0 auto; }
        .back {
            color: #c4b5fd;
            text-decoration: none;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 20px;
        }
        .back:hover { color: white; }

        h1 { margin: 0 0 10px; font-size: 2.1rem; }
        .subtitle { opacity: 0.85; margin-bottom: 25px; font-size: 1.1rem; }

        .table-container {
            background: var(--glass);
            backdrop-filter: blur(12px);
            border: 1px solid var(--border);
            border-radius: 14px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0,0,0,0.4);
        }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 14px 18px; text-align: left; }
        th { background: rgba(255,255,255,0.12); font-weight: 600; }
        tr { border-bottom: 1px solid var(--border); }
        tr:hover { background: rgba(255,255,255,0.05); }

        .action-btn {
            padding: 8px 16px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 600;
            color: white;
            transition: all 0.2s;
        }
        .btn-create-po {
            background: var(--primary);
        }
        .btn-create-po:hover { background: #7c3aed; }

        .no-records {
            text-align: center;
            padding: 80px 20px;
            opacity: 0.8;
        }
        .no-records i { font-size: 4rem; margin-bottom: 20px; }
    </style>
</head>
<body>

<div class="container">
    <a href="dashboard_store.php" class="back">
        <i class="fas fa-arrow-left"></i> Back to Store Dashboard
    </a>

    <h1>Approved Procurement Requests</h1>
    <div class="subtitle">
        Ready to Convert to Purchase Order • <?= htmlspecialchars($full_name) ?> (<?= ucfirst($user_role) ?>)
    </div>

    <div class="table-container">
        <?php if ($result->num_rows > 0): ?>
            <table>
                <thead>
                    <tr>
                        <th>PR Date</th>
                        <th>Project</th>
                        <th>Required By</th>
                        <th>Items</th>
                        <th>Total Qty</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php while ($row = $result->fetch_assoc()): ?>
                    <tr>
                        <td><?= date('d M Y', strtotime($row['pr_date'])) ?></td>
                        <td>
                            <?php if ($row['project_code']): ?>
                                <strong><?= htmlspecialchars($row['project_code']) ?></strong><br>
                                <small><?= htmlspecialchars($row['project_name']) ?></small>
                            <?php else: ?>
                                Central Request
                            <?php endif; ?>
                        </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>
                            <form action="po_create.php" method="get" style="display:inline;">
                                <input type="hidden" name="pr_id" value="<?= $row['id'] ?>">
                                <?php if ($project_id > 0): ?>
                                    <input type="hidden" name="project_id" value="<?= $project_id ?>">
                                <?php endif; ?>
                                <button type="submit" class="action-btn btn-create-po">
                                    <i class="fas fa-file-invoice"></i> Create PO
                                </button>
                            </form>
                        </td>
                    </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
        <?php else: ?>
            <div class="no-records">
                <i class="fas fa-check-circle"></i>
                <h2>No Approved PRs Pending PO Creation</h2>
                <p>All approved PRs have been converted or there are none yet.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

</body>
</html>

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