<?php
/**
 * Reset Users Page
 * GHAMECC Choir Management Platform
 * 
 * This script allows viewing and updating user credentials
 * TEMPORARY PAGE - No login required
 */

// Include database connection
require_once 'config/database.php';

// Authentication check is removed for this temporary page

// Initialize variables
$message = '';
$error = '';
$users = [];

// Function to get all users
function getAllUsers() {
    global $conn;
    $users = [];
    
    $query = "SELECT u.id, u.username, u.email, u.full_name, u.status, r.role_key, r.name as role_name 
              FROM users u
              LEFT JOIN roles r ON u.role_id = r.id
              ORDER BY u.id ASC";
    
    $result = $conn->query($query);
    
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $users[] = $row;
        }
    }
    
    return $users;
}

// Handle password reset
if (isset($_POST['reset_password'])) {
    $userId = $_POST['user_id'] ?? 0;
    $newPassword = $_POST['new_password'] ?? '';
    
    if (empty($userId) || empty($newPassword)) {
        $error = "User ID and new password are required.";
    } else {
        // Hash the new password
        $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
        
        // Update the user's password
        $stmt = $conn->prepare("UPDATE users SET password = ?, password_changed = 0 WHERE id = ?");
        $stmt->bind_param("si", $hashedPassword, $userId);
        
        if ($stmt->execute()) {
            $message = "Password reset successfully.";
        } else {
            $error = "Failed to reset password: " . $conn->error;
        }
        
        $stmt->close();
    }
}

// Handle username update
if (isset($_POST['update_username'])) {
    $userId = $_POST['user_id'] ?? 0;
    $newUsername = $_POST['new_username'] ?? '';
    
    if (empty($userId) || empty($newUsername)) {
        $error = "User ID and new username are required.";
    } else {
        // Check if username already exists
        $stmt = $conn->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
        $stmt->bind_param("si", $newUsername, $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $error = "Username already exists.";
        } else {
            // Update the username
            $stmt = $conn->prepare("UPDATE users SET username = ? WHERE id = ?");
            $stmt->bind_param("si", $newUsername, $userId);
            
            if ($stmt->execute()) {
                $message = "Username updated successfully.";
            } else {
                $error = "Failed to update username: " . $conn->error;
            }
        }
        
        $stmt->close();
    }
}

// Handle user status update
if (isset($_POST['update_status'])) {
    $userId = $_POST['user_id'] ?? 0;
    $newStatus = $_POST['new_status'] ?? '';
    
    if (empty($userId) || empty($newStatus)) {
        $error = "User ID and status are required.";
    } else {
        // Update the user's status
        $stmt = $conn->prepare("UPDATE users SET status = ? WHERE id = ?");
        $stmt->bind_param("si", $newStatus, $userId);
        
        if ($stmt->execute()) {
            $message = "User status updated successfully.";
        } else {
            $error = "Failed to update user status: " . $conn->error;
        }
        
        $stmt->close();
    }
}

// Get all users
$users = getAllUsers();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reset Users - GHAMECC Choir Management</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Custom CSS -->
    <link href="assets/css/style.css" rel="stylesheet">
    <style>
        .warning-banner {
            background-color: #f8d7da;
            color: #721c24;
            padding: 10px;
            margin-bottom: 20px;
            border: 1px solid #f5c6cb;
            border-radius: 4px;
            text-align: center;
        }
        .page-header {
            background-color: #f8f9fa;
            padding: 20px;
            margin-bottom: 20px;
            border-bottom: 1px solid #dee2e6;
        }
    </style>
</head>
<body>
    <!-- Simple Header -->
    <div class="page-header">
        <div class="container">
            <div class="d-flex justify-content-between align-items-center">
                <h1>GHAMECC Choir Management</h1>
                <a href="index.php" class="btn btn-primary">Back to Login</a>
            </div>
        </div>
    </div>
    
    <div class="container">
        <!-- Warning Banner -->
        <div class="warning-banner">
            <h4><i class="fas fa-exclamation-triangle"></i> TEMPORARY PAGE</h4>
            <p>This is a temporary page for resetting user credentials. No login is required to access this page.</p>
            <p><strong>Important:</strong> Remove or secure this page after completing necessary password resets!</p>
        </div>
        
        <div class="row">
            <!-- Main Content -->
            <main class="col-12">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">Reset Users</h1>
                </div>
                
                <?php if (!empty($message)): ?>
                <div class="alert alert-success" role="alert">
                    <?php echo htmlspecialchars($message); ?>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($error)): ?>
                <div class="alert alert-danger" role="alert">
                    <?php echo htmlspecialchars($error); ?>
                </div>
                <?php endif; ?>
                
                <!-- User Credentials Table -->
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">User Credentials</h6>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered" width="100%" cellspacing="0">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Username</th>
                                        <th>Full Name</th>
                                        <th>Email</th>
                                        <th>Role</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($users as $user): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($user['id']); ?></td>
                                        <td><?php echo htmlspecialchars($user['username']); ?></td>
                                        <td><?php echo htmlspecialchars($user['full_name']); ?></td>
                                        <td><?php echo htmlspecialchars($user['email']); ?></td>
                                        <td><?php echo htmlspecialchars($user['role_name']); ?></td>
                                        <td>
                                            <span class="badge <?php echo $user['status'] === 'active' ? 'bg-success' : 'bg-danger'; ?>">
                                                <?php echo htmlspecialchars($user['status']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#resetPasswordModal<?php echo $user['id']; ?>">
                                                <i class="fas fa-key"></i> Reset Password
                                            </button>
                                            <button type="button" class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#updateUsernameModal<?php echo $user['id']; ?>">
                                                <i class="fas fa-user-edit"></i> Update Username
                                            </button>
                                            <button type="button" class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#updateStatusModal<?php echo $user['id']; ?>">
                                                <i class="fas fa-toggle-on"></i> Update Status
                                            </button>
                                        </td>
                                    </tr>
                                    
                                    <!-- Reset Password Modal -->
                                    <div class="modal fade" id="resetPasswordModal<?php echo $user['id']; ?>" tabindex="-1" aria-labelledby="resetPasswordModalLabel<?php echo $user['id']; ?>" aria-hidden="true">
                                        <div class="modal-dialog">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title" id="resetPasswordModalLabel<?php echo $user['id']; ?>">Reset Password for <?php echo htmlspecialchars($user['username']); ?></h5>
                                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                </div>
                                                <form method="post">
                                                    <div class="modal-body">
                                                        <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                                        <div class="mb-3">
                                                            <label for="new_password<?php echo $user['id']; ?>" class="form-label">New Password</label>
                                                            <input type="password" class="form-control" id="new_password<?php echo $user['id']; ?>" name="new_password" required>
                                                        </div>
                                                    </div>
                                                    <div class="modal-footer">
                                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                        <button type="submit" name="reset_password" class="btn btn-primary">Reset Password</button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Update Username Modal -->
                                    <div class="modal fade" id="updateUsernameModal<?php echo $user['id']; ?>" tabindex="-1" aria-labelledby="updateUsernameModalLabel<?php echo $user['id']; ?>" aria-hidden="true">
                                        <div class="modal-dialog">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title" id="updateUsernameModalLabel<?php echo $user['id']; ?>">Update Username for <?php echo htmlspecialchars($user['username']); ?></h5>
                                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                </div>
                                                <form method="post">
                                                    <div class="modal-body">
                                                        <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                                        <div class="mb-3">
                                                            <label for="new_username<?php echo $user['id']; ?>" class="form-label">New Username</label>
                                                            <input type="text" class="form-control" id="new_username<?php echo $user['id']; ?>" name="new_username" value="<?php echo htmlspecialchars($user['username']); ?>" required>
                                                        </div>
                                                    </div>
                                                    <div class="modal-footer">
                                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                        <button type="submit" name="update_username" class="btn btn-primary">Update Username</button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Update Status Modal -->
                                    <div class="modal fade" id="updateStatusModal<?php echo $user['id']; ?>" tabindex="-1" aria-labelledby="updateStatusModalLabel<?php echo $user['id']; ?>" aria-hidden="true">
                                        <div class="modal-dialog">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title" id="updateStatusModalLabel<?php echo $user['id']; ?>">Update Status for <?php echo htmlspecialchars($user['username']); ?></h5>
                                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                </div>
                                                <form method="post">
                                                    <div class="modal-body">
                                                        <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                                        <div class="mb-3">
                                                            <label for="new_status<?php echo $user['id']; ?>" class="form-label">Status</label>
                                                            <select class="form-select" id="new_status<?php echo $user['id']; ?>" name="new_status" required>
                                                                <option value="active" <?php echo $user['status'] === 'active' ? 'selected' : ''; ?>>Active</option>
                                                                <option value="inactive" <?php echo $user['status'] === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                                                <option value="suspended" <?php echo $user['status'] === 'suspended' ? 'selected' : ''; ?>>Suspended</option>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    <div class="modal-footer">
                                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                        <button type="submit" name="update_status" class="btn btn-primary">Update Status</button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <!-- Default Credentials Card -->
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Default Credentials</h6>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info">
                            <p>Default credentials for testing:</p>
                            <ul>
                                <li><strong>Admin:</strong> username='admin', password='admin123'</li>
                                <li><strong>Manager:</strong> username='manager', password='manager123'</li>
                                <li><strong>Pastor:</strong> username='pastor', password='pastor123'</li>
                                <li><strong>Secretary:</strong> username='secretary', password='secretary123'</li>
                                <li><strong>Financial:</strong> username='financial', password='financial123'</li>
                                <li><strong>Member:</strong> username='member', password='member123'</li>
                                <li><strong>User:</strong> username='user', password='user123'</li>
                            </ul>
                            <p class="mb-0">Use the forms above to reset passwords if needed.</p>
                        </div>
                    </div>
                </div>
                
                <!-- Return to Login -->
                <div class="text-center mb-4">
                    <a href="login.php" class="btn btn-lg btn-primary">
                        <i class="fas fa-sign-in-alt"></i> Go to Login Page
                    </a>
                </div>
            </main>
        </div>
    </div>
    
    <!-- Bootstrap JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Custom scripts -->
    <script src="assets/js/scripts.js"></script>
</body>
</html>
