<?php
include 'db.php';
include 'layout.php';
include 'auth.php';  
include 'functions/video_help.php';

require_right('Users List');

// Check if required columns exist, if not show a message
$check_columns = $conn->query("SHOW COLUMNS FROM users LIKE 'is_active'");
if ($check_columns->num_rows === 0) {
    echo '<div class="alert alert-warning alert-dismissible fade show" role="alert">
            <i class="fa fa-exclamation-triangle"></i> 
            <strong>Database Update Required:</strong> Please run the database_updates.sql script to enable all user management features.
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
          </div>';
}

// Handle user status toggle
if (isset($_GET['toggle_status']) && isset($_GET['user_id'])) {
    $user_id = (int)$_GET['user_id'];
    // Check if is_active column exists
    $check_columns = $conn->query("SHOW COLUMNS FROM users LIKE 'is_active'");
    if ($check_columns->num_rows > 0) {
        $conn->query("UPDATE users SET is_active = NOT is_active WHERE id = $user_id");
        header("Location: users.php?success=status_updated");
        exit();
    } else {
        header("Location: users.php?error=feature_not_available");
        exit();
    }
}

// Handle user deletion
if (isset($_GET['delete_user']) && isset($_GET['user_id'])) {
    $user_id = (int)$_GET['user_id'];
    // Don't allow deletion of own account
    if ($user_id != $_SESSION['user_id']) {
        $conn->query("DELETE FROM users WHERE id = $user_id");
        header("Location: users.php?success=user_deleted");
        exit();
    } else {
        header("Location: users.php?error=cannot_delete_self");
        exit();
    }
}
?>

<div class="page-wrapper">
  <div class="content container-fluid">
        <div class="page-header d-flex justify-content-between align-items-center">
            <div class="page-title">
                <h4>User Management</h4>
                <h6>Manage system users, roles, and permissions</h6>
        </div>
            <div class="d-flex gap-2">
                <?= display_video_help_button('user_management', $conn, '<i class="fa fa-play-circle"></i> Watch Video', 'btn-outline-primary') ?>
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUserModal">
            <i class="fa fa-user-plus"></i> Add User
          </button>
                <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addRoleModal">
            <i class="fa fa-plus-circle"></i> Create Role
          </button>
      </div>
    </div>

        <!-- Success/Error Messages -->
        <?php if (isset($_GET['success'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fa fa-check-circle"></i> 
                <?php 
                switch($_GET['success']) {
                    case 'user_created': echo 'User created successfully!'; break;
                    case 'user_updated': echo 'User updated successfully!'; break;
                    case 'user_deleted': echo 'User deleted successfully!'; break;
                    case 'status_updated': echo 'User status updated!'; break;
                    case 'rights_assigned': echo 'Rights assigned successfully!'; break;
                    default: echo 'Operation completed successfully!';
                }
                ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if (isset($_GET['error'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fa fa-exclamation-triangle"></i> 
                <?php 
                switch($_GET['error']) {
                    case 'cannot_delete_self': echo 'You cannot delete your own account!'; break;
                    case 'feature_not_available': echo 'This feature requires database updates. Please run database_updates.sql first.'; break;
                    case 'duplicate_user': echo 'Username or email already exists!'; break;
                    case 'missing_fields': echo 'All required fields must be filled!'; break;
                    default: echo htmlspecialchars($_GET['error']);
                }
                ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- User Management Tabs -->
    <div class="row">
      <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <ul class="nav nav-tabs card-header-tabs" id="userTabs" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="users-tab" data-bs-toggle="tab" data-bs-target="#users" type="button" role="tab">
                                    <i class="fa fa-users"></i> Users
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="roles-tab" data-bs-toggle="tab" data-bs-target="#roles" type="button" role="tab">
                                    <i class="fa fa-user-tag"></i> Roles & Permissions
                                </button>
                            </li>
                        </ul>
                    </div>
          <div class="card-body">
                        <div class="tab-content" id="userTabsContent">
                            <!-- Users Tab -->
                            <div class="tab-pane fade show active" id="users" role="tabpanel">
            <div class="table-responsive">
                                    <table class="table table-hover datatable">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>Username</th>
                    <th>Email</th>
                    <th>Role</th>
                    <th>PIN Status</th>
                                                <th>Status</th>
                                                <th>Last Login</th>
                                                <th>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  <?php
                                            // Check if is_active column exists
                                            $check_columns = $conn->query("SHOW COLUMNS FROM users LIKE 'is_active'");
                                            $has_status_column = $check_columns->num_rows > 0;
                                            
                  $sql = "
                                                SELECT u.id, u.username, u.email, u.role_id, u.pin, u.pin_required_for_void, " . 
                                                ($has_status_column ? "u.is_active, u.last_login" : "1 as is_active, NULL as last_login") . ",
                                                r.name AS role_name
                    FROM users u
                    LEFT JOIN roles r ON u.role_id = r.id
                                                ORDER BY u.id DESC
                  ";
                  $result = $conn->query($sql);
                  $i = 1;
                  while ($row = $result->fetch_assoc()):
                                                $is_current_user = ($row['id'] == $_SESSION['user_id']);
                  ?>
                  <tr>
                    <td><?= $i++ ?></td>
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <div class="avatar avatar-sm me-2">
                                                            <span class="avatar-text rounded-circle bg-primary">
                                                                <?= strtoupper(substr($row['username'], 0, 1)) ?>
                                                            </span>
                                                        </div>
                                                        <div>
                                                            <strong><?= htmlspecialchars($row['username']) ?></strong>
                                                            <?php if ($is_current_user): ?>
                                                                <span class="badge bg-info ms-1">You</span>
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>
                                                </td>
                    <td><?= htmlspecialchars($row['email']) ?></td>
                                                <td>
                                                    <span class="badge bg-secondary"><?= htmlspecialchars($row['role_name'] ?? 'No Role') ?></span>
                                                </td>
                                                <td>
                                                    <?php if (!empty($row['pin'])): ?>
                                                        <span class="badge bg-success">Set</span>
                                                        <?php if ($row['pin_required_for_void']): ?>
                                                            <br><small class="text-muted">Void PIN: Yes</small>
                                                        <?php else: ?>
                                                            <br><small class="text-muted">Void PIN: No</small>
                                                        <?php endif; ?>
                                                    <?php else: ?>
                                                        <span class="badge bg-warning">Not Set</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if ($is_current_user): ?>
                                                        <span class="badge bg-success">Active</span>
                                                    <?php elseif ($has_status_column): ?>
                                                        <a href="?toggle_status=1&user_id=<?= $row['id'] ?>" 
                                                           class="badge <?= $row['is_active'] ? 'bg-success' : 'bg-danger' ?>"
                                                           onclick="return confirm('Toggle user status?')">
                                                            <?= $row['is_active'] ? 'Active' : 'Inactive' ?>
                                                        </a>
                                                    <?php else: ?>
                                                        <span class="badge bg-success">Active</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?= $row['last_login'] ? date('M d, Y H:i', strtotime($row['last_login'])) : 'Never' ?>
                                                </td>
                                                <td>
                                                    <div class="btn-group" role="group">
                                                        <button class="btn btn-sm btn-outline-primary" 
                                                                onclick="editUser(<?= $row['id'] ?>, '<?= htmlspecialchars($row['username']) ?>', '<?= htmlspecialchars($row['email']) ?>', <?= $row['role_id'] ?>, '<?= htmlspecialchars($row['pin'] ?? '') ?>', <?= $row['pin_required_for_void'] ? 'true' : 'false' ?>)">
                                                            <i class="fa fa-edit"></i>
                                                        </button>
                                                        <?php if (!$is_current_user): ?>
                                                            <a href="?delete_user=1&user_id=<?= $row['id'] ?>" 
                                                               class="btn btn-sm btn-outline-danger"
                                                               onclick="return confirm('Are you sure you want to delete this user?')">
                                                                <i class="fa fa-trash"></i>
                                                            </a>
                                                        <?php endif; ?>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <!-- Roles Tab -->
                            <div class="tab-pane fade" id="roles" role="tabpanel">
                                <div class="row">
                                    <div class="col-md-6">
                                        <h5>Roles</h5>
                                        <div class="table-responsive">
                                            <table class="table table-sm">
                                                <thead>
                                                    <tr>
                                                        <th>Role Name</th>
                                                        <th>Users</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
                                                    $roles = $conn->query("SELECT r.*, COUNT(u.id) as user_count FROM roles r LEFT JOIN users u ON r.id = u.role_id GROUP BY r.id");
                                                    while ($role = $roles->fetch_assoc()):
                                                    ?>
                                                    <tr>
                                                        <td><?= htmlspecialchars($role['name']) ?></td>
                                                        <td>
                                                            <span class="badge bg-info"><?= $role['user_count'] ?> users</span>
                                                        </td>
                                                        <td>
                                                            <button class="btn btn-sm btn-outline-warning" 
                                                                    onclick="assignRoleRights(<?= $role['id'] ?>, '<?= htmlspecialchars($role['name']) ?>')">
                                                                <i class="fa fa-key"></i> Permissions
                                                            </button>
                                                        </td>
                                                    </tr>
                                                    <?php endwhile; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <h5>Available Rights</h5>
                                        <div class="table-responsive">
                                            <table class="table table-sm">
                                                <thead>
                                                    <tr>
                                                        <th>Right Name</th>
                                                        <th>Category</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
                                                    $rights = $conn->query("SELECT * FROM rights ORDER BY category, name");
                                                    while ($right = $rights->fetch_assoc()):
                                                    ?>
                                                    <tr>
                                                        <td><?= htmlspecialchars($right['name']) ?></td>
                                                        <td>
                                                            <span class="badge bg-secondary"><?= htmlspecialchars($right['category'] ?? 'General') ?></span>
                                                        </td>
                  </tr>
                  <?php endwhile; ?>
                </tbody>
              </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Include Modals -->
  <?php
    include 'modals/add_user_modal.php';
    include 'modals/add_role_modal.php';
    include 'modals/assign_rights_modal.php';
    include 'modals/add_right_modal.php';
    include 'modals/edit_user_modal.php';
  ?>
</div>

<?= display_video_help_modal() ?>

<script>
function editUser(userId, username, email, roleId, pin, pinRequiredForVoid) {
    document.getElementById('edit_user_id').value = userId;
    document.getElementById('edit_username').value = username;
    document.getElementById('edit_email').value = email;
    document.getElementById('edit_role_id').value = roleId;
    document.getElementById('edit_pin').value = pin;
    document.getElementById('edit_pin_required_for_void').checked = pinRequiredForVoid === 'true';
    new bootstrap.Modal(document.getElementById('editUserModal')).show();
}

function assignRoleRights(roleId, roleName) {
    console.log('Opening modal for role:', roleId, roleName);
    
    // Open the modal first
    const modal = new bootstrap.Modal(document.getElementById('assignRightsModal'));
    modal.show();
    
    // After modal is shown, set the role in the dropdown
    setTimeout(() => {
        const roleSelect = document.querySelector('#assignRightsModal select[name="role_id"]');
        if (roleSelect) {
            console.log('Setting role select value to:', roleId);
            roleSelect.value = roleId;
            
            // Trigger the change event manually
            const event = new Event('change', { bubbles: true });
            roleSelect.dispatchEvent(event);
        } else {
            console.error('Role select not found');
        }
    }, 200); // Increased timeout to ensure modal is fully loaded
}

// Initialize DataTable
$(document).ready(function() {
    // Check if DataTable is already initialized
    if ($.fn.DataTable.isDataTable('.datatable')) {
        $('.datatable').DataTable().destroy();
    }
    
    $('.datatable').DataTable({
        stateSave: true,
        pageLength: 25
    });
});
</script>
