<?php
/**
 * User Management Page
 * GHAMECC Choir Management Platform
 */

// Include necessary files
require_once '../includes/auth.php';
require_once '../config/database.php';

// Ensure user is logged in and has appropriate permissions
requireLogin();

// Only admin and manager can access this page
if (!hasRole(['admin', 'manager'])) {
    header("Location: ../dashboard.php?error=permission_denied");
    exit;
}

// Initialize variables
$message = '';
$error = '';
$alertType = '';
$formAction = 'create';
$userId = 0;

// User data
$username = '';
$email = '';
$fullName = '';
$roleId = '';
$memberId = '';
$societyId = '';
$circuitId = '';
$dioceseId = '';
$status = 'active';

// Check for edit action
if (isset($_GET['action']) && $_GET['action'] === 'edit' && isset($_GET['id'])) {
    $userId = (int)$_GET['id'];
    $formAction = 'update';
    
    // Get user data
    $userData = fetchRow("SELECT u.*, r.role_key 
                         FROM users u 
                         LEFT JOIN roles r ON u.role_id = r.id 
                         WHERE u.id = ?", [$userId]);
    
    if ($userData) {
        $username = $userData['username'];
        $email = $userData['email'];
        $fullName = $userData['full_name'];
        $roleId = $userData['role_id'];
        $memberId = $userData['member_id'];
        $societyId = $userData['society_id'];
        $circuitId = $userData['circuit_id'];
        $dioceseId = $userData['diocese_id'];
        $status = $userData['status'];
    } else {
        $error = "User not found";
        $alertType = 'danger';
        $formAction = 'create';
    }
}

// Check for password reset action
if (isset($_GET['action']) && $_GET['action'] === 'reset_password' && isset($_GET['id'])) {
    $userId = (int)$_GET['id'];
    
    // Generate a new password
    $password = bin2hex(random_bytes(4)); // 8 characters
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
    
    // Update user password
    $result = executeQuery("UPDATE users SET password = ?, password_changed = 0 WHERE id = ?", 
                          [$hashedPassword, $userId]);
    
    if ($result) {
        $message = "Password reset successfully. New temporary password: $password";
        $alertType = 'success';
    } else {
        $error = "Failed to reset password";
        $alertType = 'danger';
    }
}

// Reset form if requested
if (isset($_GET['reset'])) {
    $formAction = 'create';
    $userId = 0;
    $username = '';
    $email = '';
    $fullName = '';
    $roleId = '';
    $memberId = '';
    $societyId = '';
    $circuitId = '';
    $dioceseId = '';
    $status = 'active';
}

// Get roles for dropdown
$roles = fetchRows("SELECT id, role_key, name FROM roles ORDER BY level DESC");

// Get societies for dropdown
$societies = fetchRows("SELECT id, name FROM societies ORDER BY name");

// Get circuits for dropdown
$circuits = fetchRows("SELECT id, name FROM circuits ORDER BY name");

// Get dioceses for dropdown
$dioceses = fetchRows("SELECT id, name FROM dioceses ORDER BY name");

// Get members for dropdown
$membersQuery = "SELECT id, CONCAT(first_name, ' ', surname) as full_name FROM members";

// When editing, include the currently assigned member
if ($formAction === 'update' && !empty($memberId)) {
    $membersQuery .= " WHERE id = $memberId OR id NOT IN (SELECT member_id FROM users WHERE member_id IS NOT NULL AND id != $userId)";
} else {
    $membersQuery .= " WHERE id NOT IN (SELECT member_id FROM users WHERE member_id IS NOT NULL)";
}

$membersQuery .= " ORDER BY first_name, surname";
$members = fetchRows($membersQuery);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get form data
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $fullName = trim($_POST['full_name']);
    $roleId = (int)$_POST['role_id'];
    $memberId = !empty($_POST['member_id']) ? (int)$_POST['member_id'] : null;
    $societyId = !empty($_POST['society_id']) ? (int)$_POST['society_id'] : null;
    $circuitId = !empty($_POST['circuit_id']) ? (int)$_POST['circuit_id'] : null;
    $dioceseId = !empty($_POST['diocese_id']) ? (int)$_POST['diocese_id'] : null;
    $status = $_POST['status'];
    $formAction = $_POST['form_action'];
    
    // Validate input
    $errors = [];
    
    if (empty($username)) {
        $errors[] = "Username is required";
    }
    
    if (empty($email)) {
        $errors[] = "Email is required";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format";
    }
    
    if (empty($fullName)) {
        $errors[] = "Full name is required";
    }
    
    if (empty($roleId)) {
        $errors[] = "Role is required";
    }
    
    // Get role key for validation
    $roleInfo = fetchRow("SELECT role_key FROM roles WHERE id = ?", [$roleId]);
    $roleKey = $roleInfo ? $roleInfo['role_key'] : '';
    
    // Validate entity selection based on role
    $societyRoles = ['choirmaster', 'society_secretary', 'society_treasurer'];
    $circuitRoles = ['circuit_secretary', 'circuit_treasurer'];
    $dioceseRoles = ['diocesan_secretary', 'diocesan_treasurer'];
    
    if (in_array($roleKey, $societyRoles) && empty($societyId)) {
        $errors[] = "Society must be selected for this role";
    }
    
    if (in_array($roleKey, $circuitRoles) && empty($circuitId)) {
        $errors[] = "Circuit must be selected for this role";
    }
    
    if (in_array($roleKey, $dioceseRoles) && empty($dioceseId)) {
        $errors[] = "Diocese must be selected for this role";
    }
    
    // Create or update user if no errors
    if (empty($errors)) {
        if ($formAction === 'create') {
            // Check if username or email already exists
            $existingUser = fetchRow("SELECT id FROM users WHERE username = ? OR email = ?", [$username, $email]);
            
            if ($existingUser) {
                $error = "Username or email already exists";
                $alertType = 'danger';
            } else {
                // Generate a random password
                $password = bin2hex(random_bytes(4)); // 8 characters
                $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                
                // Create user
                $query = "INSERT INTO users (username, password, email, full_name, role_id, member_id, 
                                           society_id, circuit_id, diocese_id, status, created_by, password_changed) 
                          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)";
                
                $userId = $_SESSION['user_id']; // Current user as creator
                
                $result = executeQuery($query, [
                    $username, $hashedPassword, $email, $fullName, $roleId, $memberId,
                    $societyId, $circuitId, $dioceseId, $status, $userId
                ]);
                
                if ($result) {
                    $message = "User created successfully. Temporary password: $password";
                    $alertType = 'success';
                    
                    // Reset form
                    $username = '';
                    $email = '';
                    $fullName = '';
                    $roleId = '';
                    $memberId = '';
                    $societyId = '';
                    $circuitId = '';
                    $dioceseId = '';
                    $status = 'active';
                } else {
                    $error = "Failed to create user";
                    $alertType = 'danger';
                }
            }
        } else if ($formAction === 'update') {
            // Update user
            $userId = (int)$_POST['user_id'];
            
            // Check if username or email already exists for another user
            $existingUser = fetchRow("SELECT id FROM users WHERE (username = ? OR email = ?) AND id != ?", 
                                    [$username, $email, $userId]);
            
            if ($existingUser) {
                $error = "Username or email already exists for another user";
                $alertType = 'danger';
            } else {
                $query = "UPDATE users SET username = ?, email = ?, full_name = ?, role_id = ?, 
                          member_id = ?, society_id = ?, circuit_id = ?, diocese_id = ?, status = ? 
                          WHERE id = ?";
                
                $result = executeQuery($query, [
                    $username, $email, $fullName, $roleId, $memberId,
                    $societyId, $circuitId, $dioceseId, $status, $userId
                ]);
                
                if ($result) {
                    $message = "User updated successfully";
                    $alertType = 'success';
                } else {
                    $error = "Failed to update user";
                    $alertType = 'danger';
                }
            }
        }
    } else {
        $error = implode("<br>", $errors);
        $alertType = 'danger';
    }
}

// Get users for listing
$users = fetchRows("SELECT u.id, u.username, u.email, u.full_name, u.status, 
                   r.name as role_name, r.role_key,
                   s.name as society_name, c.name as circuit_name, d.name as diocese_name,
                   CONCAT(m.first_name, ' ', m.surname) as member_name
                   FROM users u
                   LEFT JOIN roles r ON u.role_id = r.id
                   LEFT JOIN societies s ON u.society_id = s.id
                   LEFT JOIN circuits c ON u.circuit_id = c.id
                   LEFT JOIN dioceses d ON u.diocese_id = d.id
                   LEFT JOIN members m ON u.member_id = m.id
                   ORDER BY u.full_name");

// Include header
$pageTitle = "User Management";
?>

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar -->
        <?php include_once '../includes/sidebar.php'; ?>
        
        <!-- Main content -->
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
            <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">User Management</h1>
            </div>
            
            <?php if (!empty($message)): ?>
                <div class="alert alert-<?php echo $alertType; ?> alert-dismissible fade show" role="alert">
                    <?php echo $message; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>
            
            <?php if (!empty($error)): ?>
                <div class="alert alert-<?php echo $alertType; ?> alert-dismissible fade show" role="alert">
                    <?php echo $error; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>
            
            <!-- User Form -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="card-title mb-0"><?php echo $formAction === 'create' ? 'Create New User' : 'Edit User'; ?></h5>
                </div>
                <div class="card-body">
                    <form method="post" action="">
                        <input type="hidden" name="form_action" value="<?php echo $formAction; ?>">
                        <input type="hidden" name="user_id" value="<?php echo $userId; ?>">
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="username" class="form-label">Username <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="username" name="username" value="<?php echo htmlspecialchars($username); ?>" required>
                            </div>
                            <div class="col-md-6">
                                <label for="email" class="form-label">Email <span class="text-danger">*</span></label>
                                <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($email); ?>" required>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="full_name" class="form-label">Full Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="full_name" name="full_name" value="<?php echo htmlspecialchars($fullName); ?>" required>
                            </div>
                            <div class="col-md-6">
                                <label for="role_id" class="form-label">Role <span class="text-danger">*</span></label>
                                <select class="form-select" id="role_id" name="role_id" required>
                                    <option value="">Select Role</option>
                                    <?php foreach ($roles as $role): ?>
                                        <option value="<?php echo $role['id']; ?>" data-role-key="<?php echo $role['role_key']; ?>" <?php echo $roleId == $role['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($role['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="member_id" class="form-label">Link to Member</label>
                                <select class="form-select" id="member_id" name="member_id">
                                    <option value="">Select Member (Optional)</option>
                                    <?php foreach ($members as $member): ?>
                                        <option value="<?php echo $member['id']; ?>" <?php echo $memberId == $member['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($member['full_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="status" class="form-label">Status <span class="text-danger">*</span></label>
                                <select class="form-select" id="status" name="status" required>
                                    <option value="active" <?php echo $status === 'active' ? 'selected' : ''; ?>>Active</option>
                                    <option value="inactive" <?php echo $status === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                    <option value="suspended" <?php echo $status === 'suspended' ? 'selected' : ''; ?>>Suspended</option>
                                </select>
                            </div>
                        </div>
                        
                        <!-- Entity selection fields - shown/hidden based on role -->
                        <div class="row mb-3">
                            <div class="col-md-4 society-field" style="display: none;">
                                <label for="society_id" class="form-label">Society</label>
                                <select class="form-select" id="society_id" name="society_id">
                                    <option value="">Select Society</option>
                                    <?php foreach ($societies as $society): ?>
                                        <option value="<?php echo $society['id']; ?>" <?php echo $societyId == $society['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($society['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-4 circuit-field" style="display: none;">
                                <label for="circuit_id" class="form-label">Circuit</label>
                                <select class="form-select" id="circuit_id" name="circuit_id">
                                    <option value="">Select Circuit</option>
                                    <?php foreach ($circuits as $circuit): ?>
                                        <option value="<?php echo $circuit['id']; ?>" <?php echo $circuitId == $circuit['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($circuit['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-4 diocese-field" style="display: none;">
                                <label for="diocese_id" class="form-label">Diocese</label>
                                <select class="form-select" id="diocese_id" name="diocese_id">
                                    <option value="">Select Diocese</option>
                                    <?php foreach ($dioceses as $diocese): ?>
                                        <option value="<?php echo $diocese['id']; ?>" <?php echo $dioceseId == $diocese['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($diocese['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <button type="submit" class="btn btn-primary">
                                <?php echo $formAction === 'create' ? 'Create User' : 'Update User'; ?>
                            </button>
                            <?php if ($formAction === 'update'): ?>
                                <a href="?reset=1" class="btn btn-secondary">Cancel</a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
            </div>
            
            <!-- Users List -->
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">Users</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>Username</th>
                                    <th>Full Name</th>
                                    <th>Email</th>
                                    <th>Role</th>
                                    <th>Member</th>
                                    <th>Entity</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($users)): ?>
                                    <tr>
                                        <td colspan="8" class="text-center">No users found</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($users as $user): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($user['username']); ?></td>
                                            <td><?php echo htmlspecialchars($user['full_name']); ?></td>
                                            <td><?php echo htmlspecialchars($user['email']); ?></td>
                                            <td>
                                                <span class="badge bg-<?php echo $user['role_key'] === 'admin' ? 'danger' : ($user['role_key'] === 'manager' ? 'warning' : 'info'); ?>">
                                                    <?php echo htmlspecialchars($user['role_name']); ?>
                                                </span>
                                            </td>
                                            <td><?php echo !empty($user['member_name']) ? htmlspecialchars($user['member_name']) : '-'; ?></td>
                                            <td>
                                                <?php
                                                $entityInfo = [];
                                                if (!empty($user['society_name'])) {
                                                    $entityInfo[] = 'Society: ' . htmlspecialchars($user['society_name']);
                                                }
                                                if (!empty($user['circuit_name'])) {
                                                    $entityInfo[] = 'Circuit: ' . htmlspecialchars($user['circuit_name']);
                                                }
                                                if (!empty($user['diocese_name'])) {
                                                    $entityInfo[] = 'Diocese: ' . htmlspecialchars($user['diocese_name']);
                                                }
                                                echo !empty($entityInfo) ? implode('<br>', $entityInfo) : '-';
                                                ?>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo $user['status'] === 'active' ? 'success' : ($user['status'] === 'inactive' ? 'secondary' : 'danger'); ?>">
                                                    <?php echo ucfirst($user['status']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <div class="btn-group btn-group-sm">
                                                    <a href="?action=edit&id=<?php echo $user['id']; ?>" class="btn btn-primary">
                                                        <i class="bi bi-pencil"></i>
                                                    </a>
                                                    <a href="?action=reset_password&id=<?php echo $user['id']; ?>" class="btn btn-warning" onclick="return confirm('Reset password for this user?')">
                                                        <i class="bi bi-key"></i>
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<script>
// Show/hide entity fields based on selected role
document.addEventListener('DOMContentLoaded', function() {
    const roleSelect = document.getElementById('role_id');
    const societyField = document.querySelector('.society-field');
    const circuitField = document.querySelector('.circuit-field');
    const dioceseField = document.querySelector('.diocese-field');
    
    // Society-level roles
    const societyRoles = ['choirmaster', 'society_secretary', 'society_treasurer'];
    
    // Circuit-level roles
    const circuitRoles = ['circuit_secretary', 'circuit_treasurer'];
    
    // Diocese-level roles
    const dioceseRoles = ['diocesan_secretary', 'diocesan_treasurer'];
    
    function updateEntityFields() {
        const selectedOption = roleSelect.options[roleSelect.selectedIndex];
        const roleKey = selectedOption ? selectedOption.getAttribute('data-role-key') : '';
        
        // Show/hide society field
        societyField.style.display = societyRoles.includes(roleKey) ? 'block' : 'none';
        
        // Show/hide circuit field
        circuitField.style.display = circuitRoles.includes(roleKey) ? 'block' : 'none';
        
        // Show/hide diocese field
        dioceseField.style.display = dioceseRoles.includes(roleKey) ? 'block' : 'none';
    }
    
    // Initial update
    updateEntityFields();
    
    // Update on role change
    roleSelect.addEventListener('change', updateEntityFields);
});
</script>

<?php include_once '../includes/footer.php'; ?>
