<?php
session_start();
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include "../include/config.php";

// Session check
if (!isset($_SESSION['email'])) {
    header("location:../index.php");
    exit;
}

$userlogin = $_SESSION['email'];
$userrole  = $_SESSION['role'];
$intake    = $_SESSION['department'];

// Database connection check
if (!$conn) {
    die("Database connection failed: " . mysqli_connect_error());
}

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$message = "";

// ======================= HANDLE ADD STAFF ===========================
if (isset($_POST['addstaff'])) {
    $staffname = mysqli_real_escape_string($conn, $_POST['staffname']);
    $phone = mysqli_real_escape_string($conn, $_POST['phone']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $qualification = mysqli_real_escape_string($conn, $_POST['qualification']);
    $department = mysqli_real_escape_string($conn, $_POST['department']);
    $pass = password_hash($_POST['pass'], PASSWORD_DEFAULT);
    $gender = mysqli_real_escape_string($conn, $_POST['gender']);
    $role = mysqli_real_escape_string($conn, $_POST['role']);

    $check = mysqli_query($conn, "SELECT * FROM staff WHERE email='$email'");
    if (mysqli_num_rows($check) > 0) {
        $message = "<div class='alert alert-danger text-center'>Email already exists in the database!</div>";
    } else {
        $insert = mysqli_query($conn, "INSERT INTO staff (staffname, phone, email, qualification, department, pass, gender, role)
            VALUES ('$staffname', '$phone', '$email', '$qualification', '$department', '$pass', '$gender', '$role')");
        if ($insert) {
            $message = "<div class='alert alert-success text-center'>Staff Added Successfully!</div>";
            echo "<script>setTimeout(()=>location.href='staff.php', 1500);</script>";
        } else {
            $message = "<div class='alert alert-danger text-center'>Error: " . mysqli_error($conn) . "</div>";
        }
    }
}

// ======================= HANDLE UPDATE STAFF ===========================
if (isset($_POST['updatestaff'])) {
    $staff_id = mysqli_real_escape_string($conn, $_POST['staff_id']);
    $staffname = mysqli_real_escape_string($conn, $_POST['staffname']);
    $phone = mysqli_real_escape_string($conn, $_POST['phone']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $qualification = mysqli_real_escape_string($conn, $_POST['qualification']);
    $department = mysqli_real_escape_string($conn, $_POST['department']);
    $gender = mysqli_real_escape_string($conn, $_POST['gender']);
    $role = mysqli_real_escape_string($conn, $_POST['role']);

    $check = mysqli_query($conn, "SELECT * FROM staff WHERE email='$email' AND id!='$staff_id'");
    if (mysqli_num_rows($check) > 0) {
        $message = "<div class='alert alert-danger text-center'>Email already exists for another staff member!</div>";
    } else {
        if (!empty($_POST['pass'])) {
            $pass = password_hash($_POST['pass'], PASSWORD_DEFAULT);
            $update = mysqli_query($conn, "UPDATE staff SET staffname='$staffname', phone='$phone', email='$email', qualification='$qualification', department='$department', pass='$pass', gender='$gender', role='$role' WHERE id='$staff_id'");
        } else {
            $update = mysqli_query($conn, "UPDATE staff SET staffname='$staffname', phone='$phone', email='$email', qualification='$qualification', department='$department', gender='$gender', role='$role' WHERE id='$staff_id'");
        }

        if ($update) {
            $message = "<div class='alert alert-success text-center'>Staff Updated Successfully!</div>";
            echo "<script>setTimeout(()=>location.href='staff.php', 1500);</script>";
        } else {
            $message = "<div class='alert alert-danger text-center'>Error updating staff: " . mysqli_error($conn) . "</div>";
        }
    }
}

// ======================= HANDLE DELETE STAFF ===========================
if (isset($_GET['delete_id'])) {
    $delete_id = mysqli_real_escape_string($conn, $_GET['delete_id']);
    if (isset($_SESSION['staff_id']) && $delete_id == $_SESSION['staff_id']) {
        $message = "<div class='alert alert-danger text-center'>You cannot delete your own account!</div>";
    } else {
        $delete = mysqli_query($conn, "DELETE FROM staff WHERE id='$delete_id'");
        if ($delete) {
            $message = "<div class='alert alert-success text-center'>Staff Deleted Successfully!</div>";
            echo "<script>setTimeout(()=>location.href='staff.php', 1500);</script>";
        } else {
            $message = "<div class='alert alert-danger text-center'>Error deleting staff: " . mysqli_error($conn) . "</div>";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Staff Management</title>
  <link rel="stylesheet" href="../../boostrap/1.css">
    <link rel="stylesheet" href="../../boostrap/2.css">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600;700&family=Source+Sans+Pro:wght@300;400;600&display=swap" rel="stylesheet">

<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<!-- Bootstrap -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" crossorigin="anonymous">

<!-- jQuery & Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>

<style>
/* simplified for readability; same styling as before */
body{font-family:'Source Sans Pro',sans-serif;background:#f7f7f7;}
.card{border-radius:10px;box-shadow:0 4px 6px rgba(0,0,0,0.1);border:none;margin-bottom:20px;}
.table th{background:var(--primary);color:white;}
.staff-avatar{width:40px;height:40px;border-radius:50%;background:var(--primary);color:#fff;display:flex;align-items:center;justify-content:center;margin-right:10px;}
.staff-name{display:flex;align-items:center;}
.card-header{
    background: var(--secondary) !important;

}
.btn{
        background: var(--primary) !important;
        color: white !important;
}
</style>
</head>
<body>

<?php include "../include/nav.php"; ?>

<div class="content" style="padding:10px">
<div class="container-fluid">
<?= $message; ?>


<!-- Staff List -->
<div class="card">
<div class="card-header  text-white d-flex justify-content-between align-items-center">
<span><i class="fa fa-list"></i> Staff List</span>
<div>
<input id="searchInput" type="text" class="form-control d-inline-block" placeholder="Search..." style="width:250px;">
<button 
 class="btn btn-light btn-sm" id="refreshBtn"><i class="fa fa-refresh"></i> Refresh</button>
<button data-toggle="modal" data-target="#sms"
 class="btn btn-light btn-sm" id="refreshBtn"><i class="fa fa-graduation-cap"></i> New Staff</button>

</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table id="myTable" class="table table-striped table-hover">
<thead><tr><th>Name</th><th>Phone</th><th>Email</th><th>Qualification</th><th>Department</th><th>Gender</th><th>Role</th><th>Actions</th></tr></thead>
<tbody>
<?php
$query = mysqli_query($conn, "SELECT * FROM staff ORDER BY id DESC");
while ($row = mysqli_fetch_assoc($query)) {
$initial = substr($row['staffname'], 0, 1);
?>
<tr>
<td><div class="staff-name"><?= $row['staffname']; ?></div></td>
<td><?= $row['phone']; ?></td>
<td><?= $row['email']; ?></td>
<td><?= $row['qualification'] ?: '<span class="text-muted">N/A</span>'; ?></td>
<td><?= $row['department'] ?: '<span class="text-muted">N/A</span>'; ?></td>
<td><span class="badge badge-<?= $row['gender']=='Male'?'primary':($row['gender']=='Female'?'danger':'secondary'); ?>"><?= $row['gender']; ?></span></td>
<td><span class="badge badge-<?= 
$row['role']=='Superadmin'?'dark':
($row['role']=='Admin'?'danger':
($row['role']=='Student Affairs'?'danger':
($row['role']=='Lecturer'?'success':
($row['role']=='Finance'?'warning':
($row['role']=='Librarian'?'info':'secondary'))))); ?>"><?= $row['role']; ?></span></td>
<td>
<a href="?delete_id=<?= $row['id']; ?>" onclick="return confirm('Delete <?= $row['staffname']; ?>?')" class="btn btn-danger btn-sm"><i class="fa fa-trash"></i></a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>

</div>
</div>

<script>
$(function(){
$("#searchInput").on("keyup",function(){
var v=$(this).val().toLowerCase();
$("#myTable tbody tr").filter(function(){
$(this).toggle($(this).text().toLowerCase().indexOf(v)>-1);
});
});
$("#refreshBtn").click(()=>location.reload());
});
</script>

</body>
</html>
<div class="modal fade" id="sms" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">

  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">Add New Staff</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
       <form method="POST" id="addStaffForm">
<div class="row">
<div class="col-md-6 mb-3"><label>Staff Name *</label><input type="text" name="staffname" class="form-control" required></div>
<div class="col-md-6 mb-3"><label>Phone *</label><input type="text" name="phone" class="form-control" required></div>
<div class="col-md-6 mb-3"><label>Email *</label><input type="email" name="email" class="form-control" required></div>
<div class="col-md-6 mb-3"><label>Qualification</label><input type="text" name="qualification" class="form-control"></div>
<div class="col-md-6 mb-3"><label>Department</label><input type="text" name="department" class="form-control"></div>
<div class="col-md-6 mb-3"><label>Password *</label>
<input type="password" name="pass" id="passwordField" class="form-control" required></div>
<div class="col-md-6 mb-3"><label>Gender *</label>
<select name="gender" class="form-control" required><option value="">Select</option><option>Male</option><option>Female</option><option>Other</option></select></div>
<div class="col-md-6 mb-3"><label>Role *</label>
<select name="role" class="form-control" required><option value="">Select</option><option>Superadmin</option><option>Admin</option><option>Lecturer</option><option>Finance</option><option>Librarian</option><option>Support</option></option><option>Student Affairs</option></select></div>
</div>
<button type="submit" name="addstaff" class="btn btn-success"><i class="fa fa-save"></i> Save Staff</button>
<button type="reset" class="btn btn-secondary"><i class="fa fa-undo"></i> Reset</button>
</form>
      </div>
    </div>
  </div>
</div>