<?php
session_start();
include('db.php'); // Database connection
error_reporting(E_ALL); // Report all PHP errors
ini_set('display_errors', 1); // Display errors on the screen

// Check if the user is logged in
if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: login.php"); // Redirect to login if not logged in
    exit;
}

// Initialize search variables
$search = '';
$verifyStatus = ''; // New variable for verification status

if (isset($_GET['search'])) {
    $search = $_GET['search'];
}
if (isset($_GET['verify'])) {
    $verifyStatus = $_GET['verify'];
}

// Fetch all users with search functionality
$usersQuery = "SELECT id, name, phone, balance, profile_image, reward_points, role, pin, verify FROM users WHERE (name LIKE ? OR phone LIKE ?)";
$params = ['ss', '%' . $search . '%', '%' . $search . '%'];

// Add verification filter if set
if ($verifyStatus !== '') {
    $usersQuery .= " AND verify = ?";
    $params[0] .= 'i'; // Change parameter type
    $params[] = (int)$verifyStatus; // Add verification status to parameters
}

$stmt = $conn->prepare($usersQuery);
$stmt->bind_param(...$params);
$stmt->execute();
$usersResult = $stmt->get_result();

// Update user information
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['editUserId'])) {
    $userId = $_POST['editUserId'];
    $name = $_POST['editName'];
    $phone = $_POST['editPhone'];
    $balance = $_POST['editBalance'];
    $profileImage = $_POST['editProfileImage'];
    $rewardPoints = $_POST['editRewardPoints'];
    $role = $_POST['editRole'];
    $pin = $_POST['editPin'];
    $verify = $_POST['verify'];

    // Check if password is provided and hash it
    $password = $_POST['editPassword'] ?? null;
    if ($password) {
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        $updateQuery = "UPDATE users SET name = ?, phone = ?, balance = ?, profile_image = ?, reward_points = ?, pin = ?, verify = ?, password = ? WHERE id = ?";
        $stmt = $conn->prepare($updateQuery);
        $stmt->bind_param('ssdsssisi', $name, $phone, $balance, $profileImage, $rewardPoints, $pin, $verify, $hashedPassword, $userId);
    } else {
        $updateQuery = "UPDATE users SET name = ?, phone = ?, balance = ?, profile_image = ?, reward_points = ?, pin = ?, verify = ? WHERE id = ?";
        $stmt = $conn->prepare($updateQuery);
        $stmt->bind_param('ssdssssi', $name, $phone, $balance, $profileImage, $rewardPoints, $pin, $verify, $userId);
    }

    $stmt->execute();
    $successMessage = "User updated successfully!";
    header("Location: " . $_SERVER['PHP_SELF'] . "?search=" . urlencode($search) . "&verify=" . urlencode($verifyStatus));
    exit;
}

// Delete user
if (isset($_GET['delete'])) {
    $userId = $_GET['delete'];
    $deleteQuery = "DELETE FROM users WHERE id = ?";
    $stmt = $conn->prepare($deleteQuery);
    $stmt->bind_param('i', $userId);
    $stmt->execute();
    header("Location: " . $_SERVER['PHP_SELF'] . "?search=" . urlencode($search) . "&verify=" . urlencode($verifyStatus));
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Management</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }
        .container {
            max-width: 1200px;
            margin: 20px auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #4CAF50;
            color: white;
            padding: 1px 7px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            height: 50px;
        }
        .back-icon {
            display: flex;
            align-items: center;
            cursor: pointer;
        }
        .back-icon img {
            width: 18px;
            height: 18px;
            margin-right: 8px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 12px;
            text-align: left;
        }
        .btn {
            padding: 8px 12px;
            border-radius: 5px;
            text-decoration: none;
            cursor: pointer;
            margin-right: 10px;
        }
        .btn-delete { background-color: red; color: white; }
        .btn-edit { background-color: green; color: white; }
        .modal {
            display: none;
            position: fixed;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.3);
            z-index: 1000;
            width: 90%;
            max-width: 500px;
            overflow: hidden;
        }
        .modal-header { font-size: 20px; margin-bottom: 20px; }
        .modal-footer {
            margin-top: 20px;
            text-align: right;
        }
        .modal-footer button {
            padding: 8px 16px;
            cursor: pointer;
            border-radius: 5px;
        }
        .close-modal {
            background-color: #f44336;
            color: white;
        }
        .save-modal {
            background-color: #4CAF50;
            color: white;
        }
        .overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 500;
        }
        form {
            display: flex;
            flex-direction: column;
        }
        input[type="text"], input[type="number"], select {
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
            border: 1px solid #ddd;
            transition: border 0.3s;
        }
        input[type="text"]:focus, input[type="number"]:focus, select:focus {
            border: 1px solid #4CAF50;
            outline: none;
        }
        @media (max-width: 600px) {
            .modal {
                width: 95%;
                padding: 15px;
            }
            .modal-header {
                font-size: 18px;
            }
            .modal-footer button {
                padding: 6px 12px;
            }
        }
    </style>
</head>
<body>

<div class="header">
    <div class="back-icon" onclick="history.back();">
        <img src="https://cdn-icons-png.flaticon.com/512/93/93634.png" alt="Back">
        <span>Back</span>
    </div>
    <h3>User Management</h3>
</div>

<div class="container">
    <?php if (isset($successMessage)) echo "<p style='color: green;'>$successMessage</p>"; ?>
    
    <!-- Search Form -->
    <form method="GET" style="margin-bottom: 20px;">
        <input type="text" name="search" placeholder="Search by name or phone" value="<?php echo htmlspecialchars($search); ?>">
        <select name="verify">
            <option value="">All Users</option>
            <option value="1" <?php echo $verifyStatus == '1' ? 'selected' : ''; ?>>Verified</option>
            <option value="0" <?php echo $verifyStatus == '0' ? 'selected' : ''; ?>>Unverified</option>
        </select>
        <button type="submit" style="padding: 8px 12px; border-radius: 5px; background-color: #4CAF50; color: white; border: none;">Search</button>
    </form>

    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Phone</th>
                <th>Balance</th>
                <th>Verify Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php while ($user = $usersResult->fetch_assoc()): ?>
                <tr>
                    <td><?php echo htmlspecialchars($user['name']); ?></td>
                    <td><?php echo htmlspecialchars($user['phone']); ?></td>
                    <td><?php echo number_format($user['balance'], 2); ?></td>
                    <td><?php echo $user['verify'] == 1 ? 'Verified' : 'Unverified'; ?></td>
                    <td>
                        <button class="btn btn-edit" onclick="editUser(<?php echo $user['id']; ?>, '<?php echo htmlspecialchars($user['name']); ?>', '<?php echo htmlspecialchars($user['phone']); ?>', <?php echo $user['balance']; ?>, '<?php echo htmlspecialchars($user['profile_image']); ?>', '<?php echo $user['reward_points']; ?>', '<?php echo $user['role']; ?>', '<?php echo $user['pin']; ?>', <?php echo $user['verify']; ?>)">Edit</button>
                        <a href="?delete=<?php echo $user['id']; ?>&search=<?php echo urlencode($search); ?>&verify=<?php echo urlencode($verifyStatus); ?>" class="btn btn-delete" onclick="return confirm('Are you sure you want to delete this user?');">Delete</a>
                    </td>
                </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>

<!-- Modal for Editing User -->
<div class="modal" id="editModal">
    <div class="modal-header">Edit User</div>
    <form method="POST">
        <input type="hidden" id="editUserId" name="editUserId">
        <label for="editName">Name:</label>
        <input type="text" id="editName" name="editName" required>
        <label for="editPhone">Phone:</label>
        <input type="text" id="editPhone" name="editPhone" required>
        <label for="editBalance">Balance:</label>
        <input type="number" id="editBalance" name="editBalance" required>
        <label for="editProfileImage">Profile Image URL:</label>
        <input type="text" id="editProfileImage" name="editProfileImage">
        <label for="editRewardPoints">Reward Points:</label>
        <input type="number" id="editRewardPoints" name="editRewardPoints">
        <label for="editRole">Role:</label>
        <select id="editRole" name="editRole" required>
            <option value="bd">bd</option>
            <option value="other">other</option>
        </select>
        <label for="editPin">PIN:</label>
        <input type="text" id="editPin" name="editPin">
        <label for="editPassword">New Password:</label>
        <input type="password" id="editPassword" name="editPassword">
        <label for="verify">Verification Status:</label>
        <select id="verify" name="verify" required>
            <option value="0">Unverified</option>
            <option value="1">Verified</option>
        </select>
        <div class="modal-footer">
            <button type="button" class="close-modal" onclick="closeModal()">Cancel</button>
            <button type="submit" class="save-modal">Save Changes</button>
        </div>
    </form>
</div>
<div class="overlay" id="overlay"></div>

<script>
    function editUser(id, name, phone, balance, profileImage, rewardPoints, role, pin, verify) {
        document.getElementById('editUserId').value = id;
        document.getElementById('editName').value = name;
        document.getElementById('editPhone').value = phone;
        document.getElementById('editBalance').value = balance;
        document.getElementById('editProfileImage').value = profileImage;
        document.getElementById('editRewardPoints').value = rewardPoints;
        document.getElementById('editRole').value = role;
        document.getElementById('editPin').value = pin;
        document.getElementById('verify').value = verify;
        document.getElementById('editModal').style.display = 'block';
        document.getElementById('overlay').style.display = 'block';
    }

    function closeModal() {
        document.getElementById('editModal').style.display = 'none';
        document.getElementById('overlay').style.display = 'none';
    }
</script>

</body>
</html>
