<?php include 'services/session.php'; 

// Check if user is logged in
if (!$_SESSION['user'] || !isset($_SESSION['user'])) {
    header('Location: auth-login.php?error=session_expired');
    exit();
}

// Get user role and permissions
$user_role = $_SESSION['role_name'] ?? 'Customer';
$user_id = $_SESSION['user_id'] ?? 0;

// Check if user has permission to manage users
if (!in_array($user_role, ['Administrator'])) {
    $_SESSION['error'] = "You don't have permission to access this page.";
    header('Location: dashboard.php');
    exit();
}

// Include database connection
require_once 'layouts/dbconn.php';

// Test database connection
if (!isset($conn) || $conn->connect_error) {
    die("Database connection failed: " . ($conn->connect_error ?? 'Connection variable not set'));
}

// Handle AJAX requests
if (isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    switch ($_POST['action']) {
        case 'activate_user':
            $staff_id = (int)$_POST['staff_id'];
            $stmt = $conn->prepare("UPDATE users SET verified = 1, failed_attempts = 0 WHERE user_id = ? AND role_id != (SELECT role_id FROM user_roles WHERE role_name = 'Customer')");
            $stmt->bind_param("i", $staff_id);
            if ($stmt->execute()) {
                echo json_encode(['success' => true, 'message' => 'Staff user activated successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to activate staff user']);
            }
            $stmt->close();
            exit();
            
        case 'deactivate_user':
            $staff_id = (int)$_POST['staff_id'];
            $stmt = $conn->prepare("UPDATE users SET failed_attempts = 10 WHERE user_id = ? AND role_id != (SELECT role_id FROM user_roles WHERE role_name = 'Customer')");
            $stmt->bind_param("i", $staff_id);
            if ($stmt->execute()) {
                echo json_encode(['success' => true, 'message' => 'Staff user deactivated successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to deactivate staff user']);
            }
            $stmt->close();
            exit();
    }
}

// Get filter parameters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$role_filter = isset($_GET['role']) ? $_GET['role'] : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';

// Pagination
$records_per_page = 25;
$current_page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($current_page - 1) * $records_per_page;

// Build WHERE conditions for staff users (exclude customers)
$where_conditions = ["u.role_id != (SELECT role_id FROM user_roles WHERE role_name = 'Customer')"];
$params = [];
$param_types = '';

if (!empty($search)) {
    $where_conditions[] = "(u.full_name LIKE ? OR u.email LIKE ? OR u.username LIKE ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param]);
    $param_types .= 'sss';
}

if (!empty($role_filter)) {
    $where_conditions[] = "ur.role_name = ?";
    $params[] = $role_filter;
    $param_types .= 's';
}

if (!empty($status_filter)) {
    if ($status_filter === 'active') {
        $where_conditions[] = "u.failed_attempts < 5 AND u.verified = 1";
    } elseif ($status_filter === 'inactive') {
        $where_conditions[] = "u.failed_attempts >= 5 OR u.verified = 0";
    }
}

$where_clause = implode(' AND ', $where_conditions);

// Get total count for pagination
$count_query = "SELECT COUNT(*) as total FROM users u LEFT JOIN user_roles ur ON u.role_id = ur.role_id WHERE $where_clause";
$stmt = $conn->prepare($count_query);
if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$total_records = $stmt->get_result()->fetch_assoc()['total'];
$stmt->close();

// Calculate total pages
$total_pages = ceil($total_records / $records_per_page);

// Get staff data
$staff_query = "
    SELECT 
        u.user_id,
        u.username,
        u.email,
        u.full_name,
        u.phone,
        u.verified,
        u.failed_attempts,
        u.last_login,
        u.created_at,
        ur.role_name
    FROM users u
    LEFT JOIN user_roles ur ON u.role_id = ur.role_id
    WHERE $where_clause
    ORDER BY u.created_at DESC
    LIMIT ? OFFSET ?
";

// Add pagination parameters
$params[] = $records_per_page;
$params[] = $offset;
$param_types .= 'ii';

$stmt = $conn->prepare($staff_query);
if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$staff_result = $stmt->get_result();
$stmt->close();

// Get summary stats
$stats_query = "
    SELECT 
        COUNT(*) as total_staff,
        SUM(CASE WHEN verified = 1 AND failed_attempts < 5 THEN 1 ELSE 0 END) as active_staff,
        SUM(CASE WHEN failed_attempts >= 5 OR verified = 0 THEN 1 ELSE 0 END) as inactive_staff,
        SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as new_today
    FROM users 
    WHERE role_id != (SELECT role_id FROM user_roles WHERE role_name = 'Customer')
";

$stats_result = $conn->query($stats_query);
if ($stats_result) {
    $stats = $stats_result->fetch_assoc();
} else {
    $stats = [
        'total_staff' => 0, 
        'active_staff' => 0, 
        'inactive_staff' => 0, 
        'new_today' => 0
    ];
}

// Get roles for filter dropdown
$roles_query = "SELECT role_name FROM user_roles WHERE role_name != 'Customer' ORDER BY role_name";
$roles_result = $conn->query($roles_query);

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <?php $title = "Manage Staff Users";
    include 'partials/title-meta.php'; ?>

    <!-- SweetAlert2 -->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">

    <?php include 'partials/head-css.php'; ?>
</head>

<?php include 'partials/body.php'; ?>

<!-- Begin page -->
<div id="wrapper">

    <?php $pagetitle = "Manage Staff Users";
    include 'partials/menu.php'; ?>

    <!-- ============================================================== -->
    <!-- Start Page Content here -->
    <!-- ============================================================== -->

    <div class="content-page">
        <div class="content">

            <!-- Start Content-->
            <div class="container-fluid">
                
                <!-- start page title -->
                <div class="row">
                    <div class="col-12">
                        <div class="page-title-box">
                            <div class="page-title-right">
                                <ol class="breadcrumb m-0">
                                    <li class="breadcrumb-item"><a href="admin-dashboard.php">Dashboard</a></li>
                                    <li class="breadcrumb-item"><a href="#">Users & Customers</a></li>
                                    <li class="breadcrumb-item active">Staff Users</li>
                                </ol>
                            </div>
                            <h4 class="page-title">Manage Staff Users</h4>
                        </div>
                    </div>
                </div>
                <!-- end page title -->

                <!-- Summary Stats -->
                <div class="row">
                    <div class="col-md-3">
                        <div class="card widget-flat">
                            <div class="card-body">
                                <div class="float-end">
                                    <i class="mdi mdi-account-tie widget-icon"></i>
                                </div>
                                <h5 class="text-muted fw-normal mt-0" title="Total Staff">Total Staff</h5>
                                <h3 class="mt-3 mb-3"><?php echo number_format($stats['total_staff']); ?></h3>
                                <p class="mb-0 text-muted">
                                    <span class="text-success me-2"><i class="mdi mdi-arrow-up-bold"></i> <?php echo $stats['new_today']; ?></span>
                                    <span class="text-nowrap">New today</span>
                                </p>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="card widget-flat">
                            <div class="card-body">
                                <div class="float-end">
                                    <i class="mdi mdi-account-check widget-icon bg-success-lighten text-success"></i>
                                </div>
                                <h5 class="text-muted fw-normal mt-0" title="Active Staff">Active</h5>
                                <h3 class="mt-3 mb-3"><?php echo number_format($stats['active_staff']); ?></h3>
                                <p class="mb-0 text-muted">
                                    <span class="text-success me-2">
                                        <?php echo $stats['total_staff'] > 0 ? round(($stats['active_staff'] / $stats['total_staff']) * 100, 1) : 0; ?>%
                                    </span>
                                    <span class="text-nowrap">Active rate</span>
                                </p>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="card widget-flat">
                            <div class="card-body">
                                <div class="float-end">
                                    <i class="mdi mdi-account-off widget-icon bg-danger-lighten text-danger"></i>
                                </div>
                                <h5 class="text-muted fw-normal mt-0" title="Inactive Staff">Inactive</h5>
                                <h3 class="mt-3 mb-3"><?php echo number_format($stats['inactive_staff']); ?></h3>
                                <p class="mb-0 text-muted">
                                    <span class="text-danger me-2">
                                        <?php echo $stats['total_staff'] > 0 ? round(($stats['inactive_staff'] / $stats['total_staff']) * 100, 1) : 0; ?>%
                                    </span>
                                    <span class="text-nowrap">Inactive rate</span>
                                </p>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="card widget-flat">
                            <div class="card-body">
                                <div class="float-end">
                                    <i class="mdi mdi-plus widget-icon bg-info-lighten text-info"></i>
                                </div>
                                <h5 class="text-muted fw-normal mt-0" title="Actions">Actions</h5>
                                <div class="mt-3">
                                    <a href="add-staff.php" class="btn btn-primary btn-sm">
                                        <i class="mdi mdi-plus me-1"></i>Add Staff
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Filters and Search -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <form method="GET" id="filterForm">
                                    <div class="row">
                                        <div class="col-md-4">
                                            <div class="mb-3">
                                                <label for="search" class="form-label">Search</label>
                                                <input type="text" class="form-control" id="search" name="search" 
                                                       value="<?php echo htmlspecialchars($search); ?>" 
                                                       placeholder="Name, email, username...">
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="mb-3">
                                                <label for="role" class="form-label">Role</label>
                                                <select class="form-select" id="role" name="role">
                                                    <option value="">All Roles</option>
                                                    <?php if ($roles_result && $roles_result->num_rows > 0): ?>
                                                        <?php while ($role = $roles_result->fetch_assoc()): ?>
                                                            <option value="<?php echo htmlspecialchars($role['role_name']); ?>" 
                                                                    <?php echo $role_filter === $role['role_name'] ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($role['role_name']); ?>
                                                            </option>
                                                        <?php endwhile; ?>
                                                    <?php endif; ?>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="mb-3">
                                                <label for="status" class="form-label">Status</label>
                                                <select class="form-select" id="status" name="status">
                                                    <option value="">All Status</option>
                                                    <option value="active" <?php echo $status_filter === 'active' ? 'selected' : ''; ?>>Active</option>
                                                    <option value="inactive" <?php echo $status_filter === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-2">
                                            <div class="mb-3">
                                                <label class="form-label">&nbsp;</label>
                                                <div class="d-grid">
                                                    <button type="submit" class="btn btn-primary">
                                                        <i class="mdi mdi-magnify"></i> Search
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Staff Table -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-hover table-nowrap">
                                        <thead class="table-light">
                                            <tr>
                                                <th>Staff Member</th>
                                                <th>Contact</th>
                                                <th>Role</th>
                                                <th>Status</th>
                                                <th>Last Login</th>
                                                <th>Joined</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if ($staff_result && $staff_result->num_rows > 0): ?>
                                                <?php while ($staff = $staff_result->fetch_assoc()): ?>
                                                    <tr>
                                                        <td>
                                                            <div class="d-flex align-items-center">
                                                                <div class="avatar-sm bg-secondary rounded-circle d-flex align-items-center justify-content-center me-2">
                                                                    <span class="text-white fw-bold">
                                                                        <?php echo strtoupper(substr($staff['full_name'], 0, 2)); ?>
                                                                    </span>
                                                                </div>
                                                                <div>
                                                                    <h6 class="mb-1 fw-semibold"><?php echo htmlspecialchars($staff['full_name']); ?></h6>
                                                                    <p class="mb-0 text-muted small">@<?php echo htmlspecialchars($staff['username']); ?></p>
                                                                </div>
                                                            </div>
                                                        </td>
                                                        <td>
                                                            <div>
                                                                <i class="mdi mdi-email-outline me-1"></i>
                                                                <span class="small"><?php echo htmlspecialchars($staff['email']); ?></span>
                                                            </div>
                                                            <?php if (!empty($staff['phone'])): ?>
                                                                <div class="mt-1">
                                                                    <i class="mdi mdi-phone me-1"></i>
                                                                    <span class="small"><?php echo htmlspecialchars($staff['phone']); ?></span>
                                                                </div>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <span class="badge bg-info"><?php echo htmlspecialchars($staff['role_name']); ?></span>
                                                        </td>
                                                        <td>
                                                            <?php if ($staff['failed_attempts'] >= 5): ?>
                                                                <span class="badge bg-danger">Inactive</span>
                                                            <?php elseif ($staff['verified']): ?>
                                                                <span class="badge bg-success">Active</span>
                                                            <?php else: ?>
                                                                <span class="badge bg-warning">Pending</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <?php if ($staff['last_login']): ?>
                                                                <span class="small"><?php echo date('M j, Y H:i', strtotime($staff['last_login'])); ?></span>
                                                            <?php else: ?>
                                                                <span class="small text-muted">Never</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <span class="small"><?php echo date('M j, Y', strtotime($staff['created_at'])); ?></span>
                                                        </td>
                                                        <td>
                                                            <div class="btn-group" role="group">
                                                                <button type="button" class="btn btn-sm btn-light dropdown-toggle" 
                                                                        data-bs-toggle="dropdown" aria-expanded="false">
                                                                    <i class="mdi mdi-dots-horizontal"></i>
                                                                </button>
                                                                <ul class="dropdown-menu">
                                                                    <li><a class="dropdown-item" href="staff-detail.php?id=<?php echo $staff['user_id']; ?>">
                                                                        <i class="mdi mdi-eye me-2"></i>View Details</a></li>
                                                                    <li><a class="dropdown-item" href="edit-staff.php?id=<?php echo $staff['user_id']; ?>">
                                                                        <i class="mdi mdi-pencil me-2"></i>Edit</a></li>
                                                                    <li><hr class="dropdown-divider"></li>
                                                                    
                                                                    <?php if ($staff['failed_attempts'] >= 5 || !$staff['verified']): ?>
                                                                        <li><a class="dropdown-item text-success staff-action" href="#" 
                                                                               data-action="activate_user" data-id="<?php echo $staff['user_id']; ?>">
                                                                            <i class="mdi mdi-check me-2"></i>Activate</a></li>
                                                                    <?php else: ?>
                                                                        <li><a class="dropdown-item text-danger staff-action" href="#" 
                                                                               data-action="deactivate_user" data-id="<?php echo $staff['user_id']; ?>">
                                                                            <i class="mdi mdi-close me-2"></i>Deactivate</a></li>
                                                                    <?php endif; ?>
                                                                </ul>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endwhile; ?>
                                            <?php else: ?>
                                                <tr>
                                                    <td colspan="7" class="text-center py-5">
                                                        <div class="text-muted">
                                                            <i class="mdi mdi-account-search display-4"></i>
                                                           <p class="mt-3">No staff members found.</p>
                                                           <a href="add-staff.php" class="btn btn-primary btn-sm">Add First Staff Member</a>
                                                       </div>
                                                   </td>
                                               </tr>
                                           <?php endif; ?>
                                       </tbody>
                                   </table>
                               </div>

                               <!-- Pagination -->
                               <?php if ($total_pages > 1): ?>
                                   <div class="row">
                                       <div class="col-12">
                                           <div class="d-flex justify-content-between align-items-center mt-3">
                                               <div class="text-muted">
                                                   Showing <?php echo (($current_page - 1) * $records_per_page + 1); ?> to 
                                                   <?php echo min($current_page * $records_per_page, $total_records); ?> of 
                                                   <?php echo $total_records; ?> staff members
                                               </div>
                                               <nav aria-label="Page navigation">
                                                   <ul class="pagination pagination-sm mb-0">
                                                       <?php if ($current_page > 1): ?>
                                                           <li class="page-item">
                                                               <a class="page-link" href="?page=<?php echo ($current_page - 1); ?>&<?php echo http_build_query(array_filter($_GET, function($k) { return $k !== 'page'; }, ARRAY_FILTER_USE_KEY)); ?>">
                                                                   <i class="mdi mdi-chevron-left"></i>
                                                               </a>
                                                           </li>
                                                       <?php endif; ?>

                                                       <?php
                                                       $start_page = max(1, $current_page - 2);
                                                       $end_page = min($total_pages, $current_page + 2);
                                                       
                                                       for ($i = $start_page; $i <= $end_page; $i++):
                                                       ?>
                                                           <li class="page-item <?php echo ($i == $current_page) ? 'active' : ''; ?>">
                                                               <a class="page-link" href="?page=<?php echo $i; ?>&<?php echo http_build_query(array_filter($_GET, function($k) { return $k !== 'page'; }, ARRAY_FILTER_USE_KEY)); ?>">
                                                                   <?php echo $i; ?>
                                                               </a>
                                                           </li>
                                                       <?php endfor; ?>

                                                       <?php if ($current_page < $total_pages): ?>
                                                           <li class="page-item">
                                                               <a class="page-link" href="?page=<?php echo ($current_page + 1); ?>&<?php echo http_build_query(array_filter($_GET, function($k) { return $k !== 'page'; }, ARRAY_FILTER_USE_KEY)); ?>">
                                                                   <i class="mdi mdi-chevron-right"></i>
                                                               </a>
                                                           </li>
                                                       <?php endif; ?>
                                                   </ul>
                                               </nav>
                                           </div>
                                       </div>
                                   </div>
                               <?php endif; ?>
                           </div>
                       </div>
                   </div>
               </div>

           </div> <!-- container -->

       </div> <!-- content -->

       <?php include 'partials/footer.php'; ?>

   </div>

   <!-- ============================================================== -->
   <!-- End Page content -->
   <!-- ============================================================== -->

</div>
<!-- END wrapper -->

<?php include 'partials/right-sidebar.php'; ?>

<?php include 'partials/footer-scripts.php'; ?>

<!-- SweetAlert2 -->
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>

<!-- App js -->
<script src="assets/js/app.min.js"></script>

<script>
   $(document).ready(function() {
       // Handle staff actions
       $('.staff-action').on('click', function(e) {
           e.preventDefault();
           
           const action = $(this).data('action');
           const staffId = $(this).data('id');
           
           let title = '';
           let text = '';
           let confirmButtonText = '';
           let icon = 'warning';
           
           switch(action) {
               case 'activate_user':
                   title = 'Activate Staff User?';
                   text = 'This will activate the staff user account.';
                   confirmButtonText = 'Yes, Activate';
                   icon = 'question';
                   break;
               case 'deactivate_user':
                   title = 'Deactivate Staff User?';
                   text = 'This will deactivate the staff user account.';
                   confirmButtonText = 'Yes, Deactivate';
                   icon = 'warning';
                   break;
           }
           
           Swal.fire({
               title: title,
               text: text,
               icon: icon,
               showCancelButton: true,
               confirmButtonColor: '#3085d6',
               cancelButtonColor: '#6c757d',
               confirmButtonText: confirmButtonText,
               cancelButtonText: 'Cancel'
           }).then((result) => {
               if (result.isConfirmed) {
                   performStaffAction(action, staffId);
               }
           });
       });
       
       function performStaffAction(action, staffId) {
           $.ajax({
               url: 'manage-staff.php',
               type: 'POST',
               data: {
                  action: action,
                  staff_id: staffId
              },
              dataType: 'json',
              success: function(response) {
                  if (response.success) {
                      Swal.fire({
                          title: 'Success!',
                          text: response.message,
                          icon: 'success',
                          timer: 2000,
                          showConfirmButton: false
                      }).then(() => {
                          location.reload();
                      });
                  } else {
                      Swal.fire({
                          title: 'Error!',
                          text: response.message,
                          icon: 'error'
                      });
                  }
              },
              error: function() {
                  Swal.fire({
                      title: 'Error!',
                      text: 'An error occurred while processing the request.',
                      icon: 'error'
                  });
              }
          });
      }
      
      // Auto-submit form when filters change
      $('#role, #status').on('change', function() {
          $('#filterForm').submit();
      });
      
      // Real-time search with debounce
      let searchTimeout;
      $('#search').on('input', function() {
          clearTimeout(searchTimeout);
          searchTimeout = setTimeout(function() {
              $('#filterForm').submit();
          }, 500);
      });
  });
</script>

</body>
</html>