<?php
session_start();
// error_reporting(0);
include('includes/config.php');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if (strlen($_SESSION['alogin']) == 0) {
  header('location:index.php');
  exit;
}

// Block staff
if (isset($_GET['inid'])) {
  $id = $_GET['inid'];
  $status = 0;
  $sql = "UPDATE tblstaff SET Status=:status WHERE id=:id";
  $query = $dbh->prepare($sql);
  $query->bindParam(':id', $id, PDO::PARAM_INT);
  $query->bindParam(':status', $status, PDO::PARAM_INT);
  $query->execute();
  $_SESSION['updatemsg'] = "Staff blocked successfully";
  header('location:reg-staffs.php');
  exit;
}

// Block staff
if (isset($_GET['appid'])) {
  $id = $_GET['appid'];
  $status = 1;
  $sql = "UPDATE tblstaff SET Status=:status WHERE id=:id";
  $query = $dbh->prepare($sql);
  $query->bindParam(':id', $id, PDO::PARAM_INT);
  $query->bindParam(':status', $status, PDO::PARAM_INT);
  $query->execute();
  $_SESSION['updatemsg'] = "Staff approved successfully";
  header('location:reg-staffs.php');
  exit;
}

// Activate staff
if (isset($_GET['id'])) {
  $id = $_GET['id'];
  $status = 1;
  $sql = "UPDATE tblstaff SET Status=:status WHERE id=:id";
  $query = $dbh->prepare($sql);
  $query->bindParam(':id', $id, PDO::PARAM_INT);
  $query->bindParam(':status', $status, PDO::PARAM_INT);
  $query->execute();
  $_SESSION['updatemsg'] = "Staff activated successfully";
  header('location:reg-staffs.php');
  exit;
}
?>

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

<head>
  <meta charset="UTF-8" />
  <title>Manage Registered Staff | Library System</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="icon" type="image/x-icon" href="../<?php echo $_SESSION['logo']; ?>">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
  <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css" rel="stylesheet">
  <style>
    .square-card {
      background-color: #f8f9fa;
      border: 1px solid #dee2e6;
      border-radius: 5px;
    }

    .flash-message {
      max-width: 600px;
      margin: 0 auto 15px;
    }

    .table-wrapper {
      overflow-x: auto;
      padding: 10px;
    }

    .col-md-12 h5 {
      color: #0d6efd;
      font-size: 20px;
    }

    .dataTables_filter label {
      color: #000 !important;
      font-weight: 500;
    }

    .dataTables_filter input {
      height: 32px;
      font-size: 0.95rem;
      padding: 4px 8px;
    }

    .select2-container .select2-selection--single {
      height: 38px !important;
      display: flex;
      align-items: center;
    }

    .select2-selection__arrow {
      height: 100% !important;
    }

    .form-row>[class*="col-"] {
      margin-bottom: 0 !important;
    }

    .dataTables_length select {
      width: auto !important;
      min-width: 60px;
      padding-right: 25px;
      /* space for arrow */
    }
  </style>
</head>

<body>
  <div class="d-flex flex-column min-vh-100">
    <?php include('includes/header.php'); ?>

    <div class="main-content flex-grow-1">
      <div class="row pad-botm mb-4">
        <div class="col-md-12">
          <h5 class="header-line" style="color:#0d6efd;">MANAGE REGISTERED STAFF</h5>
        </div>
      </div>

      <div class="row justify-content-center">
        <div class="col-md-8">
          <?php foreach (['error', 'msg', 'updatemsg', 'delmsg'] as $type): ?>
            <?php if (!empty($_SESSION[$type])): ?>
              <div class="alert alert-<?php echo ($type == 'error') ? 'danger' : 'success'; ?> flash-message">
                <strong><?php echo ucfirst($type); ?> :</strong> <?php echo htmlentities($_SESSION[$type]); ?>
                <?php $_SESSION[$type] = ""; ?>
              </div>
            <?php endif; ?>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="card square-card mb-5">
        <div class="card-header bg-secondary text-white"><i class="fa fa-users mr-2"></i> Staff List</div>
        <div class="card-body table-wrapper">
          <!-- Filters -->
          <form method="GET" id="filterForm" class="mb-3">
            <div class="form-row align-items-end">

              <div class="col-md-3">
                <select name="department_id" class="form-control select2">
                  <option value="">All Departments</option>
                  <?php
                  $deptQuery = $dbh->query("SELECT department_id, department_name FROM tbldepartment ORDER BY department_name ASC");
                  while ($dept = $deptQuery->fetch(PDO::FETCH_ASSOC)) {
                    $selected = (isset($_GET['department_id']) && $_GET['department_id'] == $dept['department_id']) ? 'selected' : '';
                    echo "<option value='{$dept['department_id']}' $selected>{$dept['department_name']}</option>";
                  }
                  ?>
                </select>
              </div>

              <div class="col-md-3">
                <select name="designation_id" class="form-control select2">
                  <option value="">All Designations</option>
                  <?php
                  $designationQuery = $dbh->query("SELECT designation_id, designation_name FROM tblstaffdesignation ORDER BY designation_name ASC");
                  while ($designation = $designationQuery->fetch(PDO::FETCH_ASSOC)) {
                    $selected = (isset($_GET['designation_id']) && $_GET['designation_id'] == $designation['designation_id']) ? 'selected' : '';
                    echo "<option value='{$designation['designation_id']}' $selected>{$designation['designation_name']}</option>";
                  }
                  ?>
                </select>
              </div>
              <div class="col-md-2">
                <select name="shift" class="form-control select2">
                  <option value="">All Shifts</option>
                  <option value="1" <?= (!empty($_GET['shift']) && $_GET['shift'] == "1") ? 'selected' : '' ?>>Shift 1
                  </option>
                  <option value="2" <?= (!empty($_GET['shift']) && $_GET['shift'] == "2") ? 'selected' : '' ?>>Shift 2
                  </option>
                </select>
              </div>

              <div class="col-md-2">
                <select name="jobtype" class="form-control select2">
                  <option value="">All Job Types</option>
                  <option value="permanent" <?= (!empty($_GET['jobtype']) && $_GET['jobtype'] == "permanent") ? 'selected' : '' ?>>Permanent</option>
                  <option value="temporary" <?= (!empty($_GET['jobtype']) && $_GET['jobtype'] == "temporary") ? 'selected' : '' ?>>Temporary</option>
                </select>
              </div>

              <div class="col-md-2">
                <select name="staff_status" class="form-control select2">
                  <option value="">All Staffs</option>
                  <option value="1" <?= (!empty($_GET['staff_status']) && $_GET['staff_status'] == '1') ? 'selected' : '' ?>>Active
                  </option>
                  <option value="2" <?= (!empty($_GET['staff_status']) && $_GET['staff_status'] == '2') ? 'selected' : '' ?>>Pending
                  </option>
                  <option value="0" <?= (!empty($_GET['staff_status']) && $_GET['staff_status'] == '0') ? 'selected' : '' ?>>Blocked
                  </option>
                </select>
              </div>

              <div class="col-md-1 d-flex justify-content-end">
                <button type="submit" class="btn btn-primary mr-2">Apply</button>
              </div>
            </div>
          </form>
          <div id="staffTableContainer">
            <table id="staffTable" class="table table-bordered table-hover table-sm text-dark">
              <thead class="table-theme-header">
                <tr>
                  <th>#</th>
                  <th>Staff ID</th>
                  <th>Name</th>
                  <!-- <th>Email</th> -->
                  <th>Mobile</th>
                  <th>Department</th>
                  <th>Designation</th>
                  <th>Qualification</th>
                  <th>Status</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody>
                <?php
                $conditions = [];
                $params = [];

                // Filter: Department
                if (!empty($_GET['department_id'])) {
                  $conditions[] = "st.department_id = :department_id";
                  $params[':department_id'] = $_GET['department_id'];
                }

                // Filter: Designation
                if (!empty($_GET['designation_id'])) {
                  $conditions[] = "st.designation_id = :designation_id";
                  $params[':designation_id'] = $_GET['designation_id'];
                }
                // Filter: Shift
                if (!empty($_GET['shift'])) {
                  $conditions[] = "st.shift = :shift";
                  $params[':shift'] = $_GET['shift'];
                }
                // Filter: Job Type
                if (!empty($_GET['jobtype'])) {
                  $conditions[] = "st.jobtype = :jobtype";
                  $params[':jobtype'] = $_GET['jobtype'];
                }

                // Filter: Staff Status
                if (isset($_GET['staff_status']) && $_GET['staff_status'] !== '') {
                  $conditions[] = "st.Status = :staff_status";
                  $params[':staff_status'] = $_GET['staff_status'];
                }

                // Base Query
                $sql = "SELECT st.id AS studentprimary, st.*, d.department_name, des.designation_name 
        FROM tblstaff st
        LEFT JOIN tbldepartment d ON st.department_id=d.department_id
        LEFT JOIN tblstaffdesignation des ON st.designation_id=des.designation_id";

                // Apply filters if available
                if (!empty($conditions)) {
                  $sql .= " WHERE " . implode(' AND ', $conditions);
                }

                // Always order alphabetically
                $sql .= " ORDER BY st.FullName ASC";

                $query = $dbh->prepare($sql);
                $query->execute($params);
                $results = $query->fetchAll(PDO::FETCH_OBJ);
                $cnt = 1;
                foreach ($results as $result) {
                  ?>
                  <tr>
                    <td><?= htmlentities($cnt); ?></td>
                    <td><?= htmlentities($result->StaffId); ?></td>
                    <td class="font-weight-bold" style="color: <?php echo $_SESSION['theme_color'] ?? '#3498db'; ?>
        !important;"><?= htmlentities($result->FullName); ?></td>
                    <!-- <td><?= htmlentities($result->EmailId); ?></td> -->
                    <td><?= htmlentities($result->MobileNumber); ?></td>
                    <td><?= htmlentities($result->department_name ?? 'N/A'); ?></td>
                    <td><?= htmlentities($result->designation_name ?? 'N/A'); ?></td>
                    <td><?= htmlentities($result->Qualification ?? 'N/A'); ?></td>
                    <td>
                      <?php
                      if ($result->Status == 1) {
                        echo '<span class="badge badge-success">Active</span>';
                      } elseif ($result->Status == 0) {
                        echo '<span class="badge badge-danger">Blocked</span>';
                      } elseif ($result->Status == 2) {
                        echo '<span class="badge badge-warning">Pending</span>';
                      }
                      ?>
                    </td>
                    <td>
                      <?php if ($result->Status == 1): ?>
                        <a href="reg-staffs.php?inid=<?= $result->id; ?>" onclick="return confirm('Block this staff?');"
                          class="btn btn-sm btn-danger"><i class="fa fa-ban"></i> Block
                        </a>
                      <?php elseif ($result->Status == 0): ?>
                        <a href="reg-staffs.php?id=<?= $result->id; ?>" onclick="return confirm('Activate this staff?');"
                          class="btn btn-sm btn-primary"><i class="fa fa-check"></i> Activate
                        </a>
                      <?php elseif ($result->Status == 2): ?>
                        <!-- Pending → Approve -->
                        <a href="reg-staffs.php?appid=<?php echo htmlentities($result->id); ?>"
                          onclick="return confirm('Approve this staff?');" class="btn btn-sm btn-success">
                          <i class="fa fa-thumbs-up"></i> Approve
                        </a>
                      <?php endif; ?>
                      <a href="view-staff-profile.php?sid=<?= $result->StaffId; ?>" class="btn btn-sm btn-info"><i
                          class="fa fa-eye"></i> View
                      </a>
                      <!-- <a href="edit-staff-profile.php?sid=<?= $result->StaffId; ?>" class="btn btn-sm btn-warning"><i
                          class="fa fa-edit"></i> Edit
                      </a> -->
                    </td>
                  </tr>
                  <?php
                  $cnt++;
                }
                ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>

  <?php include('includes/footer.php'); ?>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>
  <script>
    $(document).ready(function () {
      $('#staffTable').DataTable({ pageLength: 10, lengthChange: true, responsive: true, language: { search: "🔍 Search staff:" } });
    });
  </script>
  <script>
    $(document).ready(function () {

      function initStaffTable() {
        if ($.fn.dataTable.isDataTable('#staffTable')) {
          $('#staffTable').DataTable().destroy();
        }
        $('#staffTable').DataTable({
          pageLength: 10,
          lengthChange: true,
          ordering: true,
          responsive: true,
          language: { search: "🔍 Search staff:" }
        });
      }

      initStaffTable();

      // Submit form through AJAX
      $('#filterForm').on('submit', function (e) {
        e.preventDefault();
        loadStaffTable();
      });


      function loadStaffTable() {
        const tableContainer = $('#staffTableContainer');

        $.ajax({
          url: 'reg-staffs.php', // SAME page
          type: 'GET',
          data: $('#filterForm').serialize(),
          beforeSend: function () {
            tableContainer.html('<div class="text-center p-3">Loading...</div>');
          },
          success: function (response) {
            const tableHTML = $(response).find('#staffTableContainer').html();
            tableContainer.html(tableHTML);
            initStaffTable();
          },
          error: function () {
            tableContainer.html('<div class="alert alert-danger">Failed to load data.</div>');
          }
        });
      }

    });
  </script>

  <!-- Select2 CSS -->
  <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

  <!-- Select2 JS -->
  <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

  <script>
    $(document).ready(function () {
      // Initialize select2 with placeholder and search
      $('.select2').select2({
        width: '100%',
        // placeholder: 'Select an option',
        allowClear: true
      });
    });
  </script>
</body>

</html>