<?php
/**
 * Users Management Page
 * Dozar & Tripper Management System
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/auth.php';

$user = getCurrentUser();
$pdo = getPDO();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && hasRole('admin')) {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add') {
        $username = sanitize($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        $full_name = sanitize($_POST['full_name'] ?? '');
        $role = sanitize($_POST['role'] ?? '');
        $collector_access = sanitize($_POST['collector_access'] ?? 'dozar_only');
        $can_delete = isset($_POST['can_delete']) ? 1 : 0;
        
        if ($username && $password && $full_name && $role) {
            $hashed = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO users (username, password, full_name, role, collector_access, can_delete) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$username, $hashed, $full_name, $role, $collector_access, $can_delete]);
            showMessage('User added!', 'success');
        }
    } elseif ($action === 'toggle') {
        $id = $_POST['id'] ?? '';
        if ($id) {
            $stmt = $pdo->prepare("UPDATE users SET is_active = NOT is_active WHERE id=?");
            $stmt->execute([$id]);
            showMessage('User status toggled!', 'success');
        }
    } elseif ($action === 'toggle_delete') {
        $id = $_POST['id'] ?? '';
        if ($id) {
            $stmt = $pdo->prepare("UPDATE users SET can_delete = NOT can_delete WHERE id=?");
            $stmt->execute([$id]);
            showMessage('Delete authority toggled!', 'success');
        }
    }
}

$users = $pdo->query("SELECT * FROM users ORDER BY full_name")->fetchAll();

// Get projects for dropdown
$projects = [];
$stmt = $pdo->query("SELECT * FROM projects WHERE is_active = 1");
while ($row = $stmt->fetch()) {
    $projects[$row['id']] = $row['project_name'];
}
?>
<?php include __DIR__ . '/../includes/header.php'; ?>

<div class="row">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-user-cog"></i> Users</h2>
            <?php if (hasRole('admin')): ?>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addModal">
                <i class="fas fa-plus"></i> Add User
            </button>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php displayMessage(); ?>

<div class="card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Username</th>
                        <th>Full Name</th>
                        <th>Role</th>
                        <th>Access</th>
                        <th>Delete Auth</th>
                        <th>Status</th>
                        <?php if (hasRole('admin')): ?>
                        <th>Actions</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $u): ?>
                    <tr>
                        <td><?php echo $u['username']; ?></td>
                        <td><?php echo $u['full_name']; ?></td>
                        <td><span class="badge bg-<?php echo $u['role'] == 'admin' ? 'danger' : ($u['role'] == 'viewer' ? 'info' : 'primary'); ?>"><?php echo ucfirst($u['role']); ?></span></td>
                        <td><?php echo $u['collector_access'] ? str_replace('_', ' ', ucwords($u['collector_access'], '_')) : '-'; ?></td>
                        <td>
                            <?php if ($u['role'] === 'collector'): ?>
                                <form method="POST" style="display:inline;">
                                    <input type="hidden" name="action" value="toggle_delete">
                                    <input type="hidden" name="id" value="<?php echo $u['id']; ?>">
                                    <button type="submit" class="btn btn-sm <?php echo $u['can_delete'] ? 'btn-danger' : 'btn-outline-secondary'; ?>" title="<?php echo $u['can_delete'] ? 'Revoke Delete Authority' : 'Grant Delete Authority'; ?>">
                                        <i class="fas fa-trash-alt"></i> <?php echo $u['can_delete'] ? 'Allowed' : 'Denied'; ?>
                                    </button>
                                </form>
                            <?php elseif ($u['role'] === 'admin'): ?>
                                <span class="badge bg-danger">Full Access</span>
                            <?php else: ?>
                                <span class="badge bg-secondary">N/A</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="badge bg-<?php echo $u['is_active'] ? 'success' : 'secondary'; ?>">
                                <?php echo $u['is_active'] ? 'Active' : 'Inactive'; ?>
                            </span>
                        </td>
                        <?php if (hasRole('admin')): ?>
                        <td>
                            <a href="view.php?id=<?php echo $u['id']; ?>" class="btn btn-sm btn-info">
                                <i class="fas fa-eye"></i>
                            </a>
                            <form method="POST" style="display:inline;">
                                <input type="hidden" name="action" value="toggle">
                                <input type="hidden" name="id" value="<?php echo $u['id']; ?>">
                                <button type="submit" class="btn btn-sm btn-<?php echo $u['is_active'] ? 'warning' : 'success'; ?>">
                                    <i class="fas fa-toggle-<?php echo $u['is_active'] ? 'off' : 'on'; ?>"></i>
                                </button>
                            </form>
                        </td>
                        <?php endif; ?>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php if (hasRole('admin')): ?>
<div class="modal fade" id="addModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add User</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="add">
                    <div class="mb-3">
                        <label class="form-label">Username *</label>
                        <input type="text" name="username" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Full Name *</label>
                        <input type="text" name="full_name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Password *</label>
                        <input type="password" name="password" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Role *</label>
                        <select name="role" class="form-select" id="roleSelect" onchange="toggleAccess()">
                            <option value="admin">Admin</option>
                            <option value="collector">Collector</option>
                            <option value="viewer">Viewer</option>
                        </select>
                    </div>
                    <div class="mb-3" id="accessField" style="display:none;">
                        <label class="form-label">Collector Access</label>
                        <select name="collector_access" class="form-select">
                            <option value="dozar_only">Dozar Only</option>
                            <option value="tripper_loading_only">Tripper Loading Only</option>
                            <option value="tripper_unloading_only">Tripper Unloading Only</option>
                            <option value="all_modules">All Modules</option>
                        </select>
                    </div>
                    <div class="mb-3 form-check" id="canDeleteField" style="display:none;">
                        <input type="checkbox" name="can_delete" class="form-check-input" id="canDeleteCheck">
                        <label class="form-check-label" for="canDeleteCheck">Grant Delete Authority</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Add User</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>
<script>
function toggleAccess() {
    var role = document.getElementById('roleSelect').value;
    document.getElementById('accessField').style.display = (role === 'collector') ? 'block' : 'none';
    document.getElementById('canDeleteField').style.display = (role === 'collector') ? 'block' : 'none';
}
</script>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
