<?php
session_start();
if (!isset($_SESSION['unohs'])) { header("location:index.php"); exit; }
include "../deepanshu/conn.php";

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $id = intval($_POST['id']);
    if ($_POST['action'] === 'approve') {
        $row = $conn->query("SELECT * FROM password_reset_requests WHERE id = $id AND status = 'pending'")->fetch_assoc();
        if ($row) {
            $md5pwd = md5($row['new_password']);
            $mobileEsc = mysqli_real_escape_string($conn, $row['mobile']);
            $conn->query("UPDATE shonu_subjects SET password = '$md5pwd', pwd = '{$row['new_password']}' WHERE mobile = '$mobileEsc'");
            $conn->query("UPDATE password_reset_requests SET status = 'approved', processed_at = NOW() WHERE id = $id");
        }
    } elseif ($_POST['action'] === 'reject') {
        $conn->query("UPDATE password_reset_requests SET status = 'rejected', processed_at = NOW() WHERE id = $id");
    }
    header("Location: admin_password_resets.php");
    exit;
}

$requests = $conn->query("SELECT * FROM password_reset_requests WHERE status = 'pending' ORDER BY created_at DESC");
?>
<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8">
<title>Password Reset Requests</title>
<style>
    body { background: #0a0a0a; color: #fff; font-family: sans-serif; padding: 20px; }
    table { width: 100%; border-collapse: collapse; }
    th, td { padding: 12px; border-bottom: 1px solid #333; text-align: left; font-size: 13px; }
    th { color: #ffd54f; }
    .btn-approve { background: #22D67A; color: #000; padding: 6px 12px; border: none; border-radius: 6px; cursor: pointer; font-weight: 700; }
    .btn-reject { background: #FF5C7A; color: #fff; padding: 6px 12px; border: none; border-radius: 6px; cursor: pointer; margin-left: 6px; font-weight: 700; }
</style>
</head>
<body>
<h2>🔑 Password Reset Requests (Pending)</h2>
<table>
<tr><th>Mobile</th><th>New Password</th><th>Verification Note</th><th>Time</th><th>Action</th></tr>
<?php while ($row = $requests->fetch_assoc()): ?>
<tr>
    <td><?= htmlspecialchars($row['mobile']) ?></td>
    <td><?= htmlspecialchars($row['new_password']) ?></td>
    <td><?= htmlspecialchars($row['verification_note']) ?></td>
    <td><?= htmlspecialchars($row['created_at']) ?></td>
    <td>
        <form method="POST" style="display:inline;">
            <input type="hidden" name="id" value="<?= $row['id'] ?>">
            <button class="btn-approve" name="action" value="approve" onclick="return confirm('নিশ্চিত? এই Password Active হয়ে যাবে।')">Approve</button>
            <button class="btn-reject" name="action" value="reject">Reject</button>
        </form>
    </td>
</tr>
<?php endwhile; ?>
</table>
</body>
</html>
