<?php
$pageTitle = 'Users';
require_once __DIR__ . '/includes/header.php';

$db = Database::getInstance();
$roles = $db->query("SELECT id, name FROM roles ORDER BY id ASC")->fetchAll();
$restaurants = $db->query("SELECT id, name FROM restaurants ORDER BY name ASC")->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <form class="d-flex gap-2" method="GET">
            <select name="role" class="form-select form-select-sm" style="width:150px;">
                <option value="">All Roles</option>
                <?php foreach ($roles as $r): ?>
                    <option value="<?php echo $r['id']; ?>" <?php echo ($_GET['role'] ?? '') == $r['id'] ? 'selected' : ''; ?>><?php echo ucfirst(str_replace('_', ' ', $r['name'])); ?></option>
                <?php endforeach; ?>
            </select>
            <select name="restaurant_id" class="form-select form-select-sm" style="width:180px;">
                <option value="">All Restaurants</option>
                <?php foreach ($restaurants as $rest): ?>
                    <option value="<?php echo $rest['id']; ?>" <?php echo ($_GET['restaurant_id'] ?? '') == $rest['id'] ? 'selected' : ''; ?>><?php echo sanitize($rest['name']); ?></option>
                <?php endforeach; ?>
            </select>
            <button type="submit" class="btn btn-sm btn-primary"><i class="fas fa-search"></i></button>
            <a href="users.php" class="btn btn-sm btn-outline-secondary">Reset</a>
        </form>
    </div>
    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#userModal" onclick="resetUserForm()"><i class="fas fa-plus me-1"></i>Add User</button>
</div>

<div class="table-card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover datatable">
                <thead class="table-light">
                    <tr>
                        <th>ID</th><th>Name</th><th>Email</th><th>Role</th><th>Restaurant</th>
                        <th>Status</th><th>Last Login</th><th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $sql = "SELECT u.*, r.name as role_name, rst.name as restaurant_name
                            FROM users u
                            LEFT JOIN roles r ON u.role_id = r.id
                            LEFT JOIN restaurants rst ON u.restaurant_id = rst.id
                            WHERE 1=1";
                    $params = [];
                    if (!empty($_GET['role'])) {
                        $sql .= " AND u.role_id = ?";
                        $params[] = (int) $_GET['role'];
                    }
                    if (!empty($_GET['restaurant_id'])) {
                        $sql .= " AND u.restaurant_id = ?";
                        $params[] = (int) $_GET['restaurant_id'];
                    }
                    $sql .= " ORDER BY u.created_at DESC";
                    $users = $db->query($sql, $params)->fetchAll();
                    ?>
                    <?php foreach ($users as $u): ?>
                    <tr>
                        <td><?php echo $u['id']; ?></td>
                        <td>
                            <div class="d-flex align-items-center">
                                <div class="avatar-circle me-2" style="width:28px;height:28px;font-size:12px;"><?php echo strtoupper(substr($u['name'], 0, 1)); ?></div>
                                <?php echo sanitize($u['name']); ?>
                            </div>
                        </td>
                        <td><?php echo sanitize($u['email']); ?></td>
                        <td><span class="badge bg-secondary"><?php echo ucfirst(str_replace('_', ' ', $u['role_name'] ?? 'N/A')); ?></span></td>
                        <td><?php echo sanitize($u['restaurant_name'] ?? 'System'); ?></td>
                        <td><span class="badge bg-<?php echo $u['status'] === 'active' ? 'success' : 'secondary'; ?>"><?php echo ucfirst($u['status']); ?></span></td>
                        <td><?php echo $u['last_login'] ? timeAgo($u['last_login']) : 'Never'; ?></td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary btn-action edit-user-btn" data-id="<?php echo $u['id']; ?>" data-name="<?php echo sanitize($u['name']); ?>" data-email="<?php echo sanitize($u['email']); ?>" data-role="<?php echo $u['role_id']; ?>" data-restaurant="<?php echo $u['restaurant_id'] ?? ''; ?>" data-status="<?php echo $u['status']; ?>" data-phone="<?php echo sanitize($u['phone'] ?? ''); ?>" title="Edit"><i class="fas fa-edit"></i></button>
                            <button class="btn btn-sm btn-outline-warning btn-action reset-pwd-btn" data-id="<?php echo $u['id']; ?>" data-name="<?php echo sanitize($u['name']); ?>" title="Reset Password"><i class="fas fa-key"></i></button>
                            <button class="btn btn-sm btn-outline-danger btn-action toggle-user-btn" data-id="<?php echo $u['id']; ?>" data-status="<?php echo $u['status']; ?>" title="Toggle Status"><i class="fas fa-toggle-<?php echo $u['status'] === 'active' ? 'on text-success' : 'off text-danger'; ?>"></i></button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="userModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="userModalTitle">Add User</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="userForm" action="user_save.php" method="POST">
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                    <input type="hidden" name="user_id" id="user_id" value="">
                    <div class="mb-3">
                        <label class="form-label">Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="name" id="user_name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Email <span class="text-danger">*</span></label>
                        <input type="email" class="form-control" name="email" id="user_email" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Password <span id="pwdRequired" class="text-danger">*</span></label>
                        <input type="password" class="form-control" name="password" id="user_password" minlength="6">
                        <small class="text-muted" id="pwdHint">Leave blank to keep current password.</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Phone</label>
                        <input type="text" class="form-control" name="phone" id="user_phone">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Role <span class="text-danger">*</span></label>
                        <select class="form-select" name="role_id" id="user_role" required>
                            <?php foreach ($roles as $r): ?>
                                <option value="<?php echo $r['id']; ?>"><?php echo ucfirst(str_replace('_', ' ', $r['name'])); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Restaurant</label>
                        <select class="form-select" name="restaurant_id" id="user_restaurant">
                            <option value="">-- None --</option>
                            <?php foreach ($restaurants as $rest): ?>
                                <option value="<?php echo $rest['id']; ?>"><?php echo sanitize($rest['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select class="form-select" name="status" id="user_status">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save me-1"></i>Save User</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function resetUserForm() {
    document.getElementById('userModalTitle').textContent = 'Add User';
    document.getElementById('userForm').reset();
    document.getElementById('user_id').value = '';
    document.getElementById('pwdRequired').style.display = '';
    document.getElementById('pwdHint').style.display = 'none';
}

document.querySelectorAll('.edit-user-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        document.getElementById('userModalTitle').textContent = 'Edit User';
        document.getElementById('user_id').value = this.dataset.id;
        document.getElementById('user_name').value = this.dataset.name;
        document.getElementById('user_email').value = this.dataset.email;
        document.getElementById('user_phone').value = this.dataset.phone;
        document.getElementById('user_role').value = this.dataset.role;
        document.getElementById('user_restaurant').value = this.dataset.restaurant;
        document.getElementById('user_status').value = this.dataset.status;
        document.getElementById('pwdRequired').style.display = 'none';
        document.getElementById('pwdHint').style.display = '';
        document.getElementById('user_password').removeAttribute('required');
        new bootstrap.Modal(document.getElementById('userModal')).show();
    });
});

document.querySelectorAll('.reset-pwd-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var id = this.dataset.id;
        var name = this.dataset.name;
        var newPass = prompt('Enter new password for ' + name + ':');
        if (newPass && newPass.length >= 6) {
            ajaxPost(BASE_URL + '/admin/user_save.php', 'action=reset_password&user_id=' + id + '&password=' + encodeURIComponent(newPass) + '&csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(data) {
                if (data.success) {
                    showAlert('success', data.message);
                } else {
                    showAlert('danger', data.message);
                }
            });
        } else if (newPass !== null) {
            alert('Password must be at least 6 characters.');
        }
    });
});

document.querySelectorAll('.toggle-user-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var id = this.dataset.id;
        var current = this.dataset.status;
        var newStatus = current === 'active' ? 'inactive' : 'active';
        if (confirm('Change user status to ' + newStatus + '?')) {
            ajaxPost(BASE_URL + '/admin/user_save.php', 'action=toggle_status&user_id=' + id + '&status=' + newStatus + '&csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(data) {
                if (data.success) {
                    showAlert('success', data.message);
                    setTimeout(function() { location.reload(); }, 1000);
                } else {
                    showAlert('danger', data.message);
                }
            });
        }
    });
});
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
