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

// Only Store Manager or Admin can access
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], ['store manager', 'admin'])) {
    header("Location: ../login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role'];
$full_name = $_SESSION['full_name'] ?? 'Store Manager';

$success = "";
$error = "";

// Handle Approve / Reject Actions
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['pr_id']) && isset($_POST['action'])) {
    $pr_id = (int)$_POST['pr_id'];
    $action = $_POST['action']; // approve or reject
    $new_status = $action === 'approve' ? 'Approved' : 'Rejected';

    $stmt = $conn->prepare("
        UPDATE procurement_request 
        SET status = ?, approved_by = ?, approved_at = NOW()
        WHERE id = ? AND status = 'Pending'
    ");
    $stmt->bind_param("sii", $new_status, $user_id, $pr_id);
    $stmt->execute();

    if ($stmt->affected_rows > 0) {
        $success = "PR #" . str_pad($pr_id, 5, '0', STR_PAD_LEFT) . " has been " . $new_status . " successfully!";
    } else {
        $error = "Failed to update PR. It may have already been processed.";
    }
}

// Fetch Pending Procurement Requests
$query = "
    SELECT 
        pr.id,
        pr.project_id AS project_id,
        pr.pr_date,
        pr.required_by_date,
        pr.remarks,
        u.full_name AS raised_by,
        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 users u ON pr.requested_by = u.id
    LEFT JOIN project_master p ON pr.project_id = p.id
    LEFT JOIN procurement_request_items pri ON pr.id = pri.pr_id
    WHERE pr.status = 'Pending'
    GROUP BY pr.id
    ORDER BY pr.pr_date DESC, pr.id DESC
";

$result = $conn->query($query);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pending PR Approvals</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: 1280px; 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;
        }
        .header h1 {
            font-size: clamp(28px, 5.5vw, 40px);
            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);
        }

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

        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;
            font-weight: 600;
        }
        td {
            padding: 18px 16px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }

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

        .status-badge {
            padding: 8px 18px;
            border-radius: 50px;
            font-size: 0.9rem;
            font-weight: 700;
            background: rgba(245,158,11,0.25);
            color: #fcd34d;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        .btn {
            padding: 10px 18px;
            border: none;
            border-radius: 12px;
            cursor: pointer;
            font-weight: 700;
            font-size: 0.95rem;
            transition: all 0.3s;
        }
        .btn-approve {
            background: #22c55e;
            color: white;
        }
        .btn-approve:hover { background: #16a34a; transform: translateY(-2px); }
        .btn-reject {
            background: #ef4444;
            color: white;
        }
        .btn-reject:hover { background: #dc2626; transform: translateY(-2px); }
        .btn-view {
            background: var(--primary);
            color: white;
        }
        .btn-view:hover { background: #9333ea; transform: translateY(-2px); }

        .message {
            padding: 16px 24px;
            border-radius: 16px;
            margin: 20px 40px;
            font-weight: 600;
        }
        .success { background: rgba(34,197,94,0.25); border:1px solid #4ade80; color:#86efac; }
        .error   { background: rgba(239,68,68,0.25); border:1px solid #f87171; color:#fca5a5; }

        .no-data {
            text-align: center;
            padding: 80px 20px;
            color: #94a3b8;
        }
        .no-data i { font-size: 4rem; margin-bottom: 20px; opacity: 0.6; }

        @media (max-width: 768px) {
            .header, .top-bar, .table-container { padding: 25px 20px; }
            table { font-size: 0.95rem; }
            th, td { padding: 14px 10px; }
            .action-buttons { flex-direction: column; }
        }
    </style>
</head>
<body>
<?php include '../config/header.php'; ?>

<div class="container">
    <div class="glass-container">
        <div class="header">
            <a href="dashboard_store.php" style="color:#c4b5fd; text-decoration:none; position:absolute; left:40px; top:50px;">
                ← Back to Dashboard
            </a>
            <h1><i class="fas fa-clipboard-check"></i> Pending PR Approvals</h1>
            <p style="margin-top:12px; opacity:0.9;">
                <?= htmlspecialchars($full_name) ?> • <?= ucfirst($user_role) ?>
            </p>
        </div>

        <div class="top-bar">
            <h2 style="margin:0;">Pending Procurement Requests</h2>
            <span style="background:rgba(245,158,11,0.2); color:#fcd34d; padding:8px 18px; border-radius:50px; font-weight:600;">
                <?= $result->num_rows ?> Pending
            </span>
        </div>

        <?php if ($success): ?>
            <div class="message success"><?= htmlspecialchars($success) ?></div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="message error"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <div class="table-container">
            <?php if ($result->num_rows > 0): ?>
                <table>
                    <thead>
                        <tr>
                            <th>PR No</th>
                            <th>Date</th>
                            <th>Project</th>
                            <th>Raised By</th>
                            <th>Items</th>
                            <th>Total Qty</th>
                            <th style="text-align:center;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php while ($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td class="pr-number">PR-<?= str_pad($row['id'], 5, '0', STR_PAD_LEFT) ?></td>
                            <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: ?>
                                    <em>Central Request</em>
                                <?php endif; ?>
                            </td>
                            <td><?= htmlspecialchars($row['raised_by'] ?? 'Unknown') ?></td>
                            <td><strong><?= $row['item_count'] ?></strong> items</td>
                            <td><?= number_format($row['total_qty'], 2) ?></td>
                            <td class="action-buttons" style="text-align:center;">
                                <form method="post" style="display:inline;">
                                    <input type="hidden" name="pr_id" value="<?= $row['id'] ?>">
                                    <button type="submit" name="action" value="approve" class="btn btn-approve">
                                        <i class="fas fa-check"></i> Approve
                                    </button>
                                </form>

                                <form method="post" style="display:inline;">
                                    <input type="hidden" name="pr_id" value="<?= $row['id'] ?>">
                                    <button type="submit" name="action" value="reject" class="btn btn-reject">
                                        <i class="fas fa-times"></i> Reject
                                    </button>
                                </form>

                                <a href="pr_view.php?pr_id=<?= $row['id'] ?>" class="btn btn-view">
                                    <i class="fas fa-eye"></i> View
                                </a>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="no-data">
                    <i class="fas fa-check-circle"></i>
                    <h2>No Pending Requests</h2>
                    <p>All procurement requests have been processed.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

</body>
</html>

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