<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
include('includes/db.php');
include('includes/header.php');

/* ================= CSRF ================= */
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

/* ================= AUTH ================= */
if (empty($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

/* ================= FACILITY LOCK ================= */
if (empty($_SESSION['facility_id'])) {
    $_SESSION['flash'] = [
        'message' => 'No facility assigned to your account.',
        'color'   => '#dc3545'
    ];
    header("Location: login.php");
    exit;
}

$facility_id = (int)$_SESSION['facility_id'];
$user_id     = (int)$_SESSION['user_id'];
$user_role   = $_SESSION['user_role'] ?? '';

/* ================= FETCH DEPARTMENTS (FACILITY ONLY) ================= */
$deptStmt = $pdo->prepare("
    SELECT id, name
    FROM departments
    WHERE facility_id=?
    ORDER BY name ASC
");
$deptStmt->execute([$facility_id]);
$departments = $deptStmt->fetchAll(PDO::FETCH_ASSOC);

/* ================= USER ROLES ================= */
$userRoles = [
    'Super_admin','Admin','Staff','Doctor','Nurse','Lab_technician','Pharmacist',
    'Receptionist','Radiologist','Accountant','Cashier','Cleaner','Security',
    'Driver','Manager','Dentist'
];

/* ================= HANDLE CRUD ================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (($_POST['csrf'] ?? '') !== $csrf) {
        die("Invalid CSRF token");
    }

    /* ---------- CREATE USER ---------- */
    if (isset($_POST['create'])) {

        $username    = trim($_POST['username']);
        $email       = trim($_POST['email']);
        $phone       = trim($_POST['phone']);
        $password    = $_POST['password'];
        $confirm     = $_POST['confirm_password'];
        $dept_id     = !empty($_POST['department_id']) ? (int)$_POST['department_id'] : null;
        $role        = $_POST['user_role'];
        $status      = $_POST['status'];
        $license_no  = trim($_POST['license_number'] ?? ''); // ADDED LICENSE NUMBER

        if ($password !== $confirm) {
            $_SESSION['flash'] = ['message'=>'Passwords do not match','color'=>'#dc3545'];
            header("Location: ".$_SERVER['PHP_SELF']); exit;
        }

        /* USERNAME UNIQUE PER FACILITY */
        $stmt = $pdo->prepare("
            SELECT 1 FROM users
            WHERE username=? AND facility_id=?
            LIMIT 1
        ");
        $stmt->execute([$username, $facility_id]);
        if ($stmt->fetchColumn()) {
            $_SESSION['flash'] = ['message'=>'Username already exists in this facility','color'=>'#dc3545'];
            header("Location: ".$_SERVER['PHP_SELF']); exit;
        }

        /* EMAIL UNIQUE PER FACILITY */
        $stmt = $pdo->prepare("
            SELECT 1 FROM users
            WHERE email=? AND facility_id=?
            LIMIT 1
        ");
        $stmt->execute([$email, $facility_id]);
        if ($stmt->fetchColumn()) {
            $_SESSION['flash'] = ['message'=>'Email already exists in this facility','color'=>'#dc3545'];
            header("Location: ".$_SERVER['PHP_SELF']); exit;
        }

        $hash = password_hash($password, PASSWORD_DEFAULT);

        $stmt = $pdo->prepare("
            INSERT INTO users
            (username,email,phone,password_hash,department_id,facility_id,user_role,status,license_number)
            VALUES (?,?,?,?,?,?,?,?,?)
        ");
        $stmt->execute([
            $username,
            $email,
            $phone,
            $hash,
            $dept_id,
            $facility_id,
            $role,
            $status,
            $license_no  // ADDED LICENSE NUMBER
        ]);

        $_SESSION['flash'] = ['message'=>'User created successfully','color'=>'#28a745'];
        header("Location: ".$_SERVER['PHP_SELF']); exit;
    }

    /* ---------- UPDATE USER ---------- */
    if (isset($_POST['update'])) {

        $id          = (int)$_POST['id'];
        $username    = trim($_POST['username']);
        $email       = trim($_POST['email']);
        $phone       = trim($_POST['phone']);
        $password    = $_POST['password'];
        $confirm     = $_POST['confirm_password'];
        $dept_id     = !empty($_POST['department_id']) ? (int)$_POST['department_id'] : null;
        $role        = $_POST['user_role'];
        $status      = $_POST['status'];
        $license_no  = trim($_POST['license_number'] ?? ''); // ADDED LICENSE NUMBER

        /* OWNERSHIP CHECK */
        $stmt = $pdo->prepare("
            SELECT 1 FROM users
            WHERE id=? AND facility_id=?
        ");
        $stmt->execute([$id, $facility_id]);
        if (!$stmt->fetchColumn()) {
            $_SESSION['flash'] = ['message'=>'Unauthorized update','color'=>'#dc3545'];
            header("Location: ".$_SERVER['PHP_SELF']); exit;
        }

        /* USERNAME DUPLICATE CHECK PER FACILITY */
        $stmt = $pdo->prepare("
            SELECT 1 FROM users
            WHERE username=? AND facility_id=? AND id<>?
            LIMIT 1
        ");
        $stmt->execute([$username, $facility_id, $id]);
        if ($stmt->fetchColumn()) {
            $_SESSION['flash'] = ['message'=>'Username already exists in this facility','color'=>'#dc3545'];
            header("Location: ".$_SERVER['PHP_SELF']); exit;
        }

        /* EMAIL DUPLICATE CHECK PER FACILITY */
        $stmt = $pdo->prepare("
            SELECT 1 FROM users
            WHERE email=? AND facility_id=? AND id<>?
            LIMIT 1
        ");
        $stmt->execute([$email, $facility_id, $id]);
        if ($stmt->fetchColumn()) {
            $_SESSION['flash'] = ['message'=>'Email already exists in this facility','color'=>'#dc3545'];
            header("Location: ".$_SERVER['PHP_SELF']); exit;
        }

        if (!empty($password)) {
            if ($password !== $confirm) {
                $_SESSION['flash'] = ['message'=>'Passwords do not match','color'=>'#dc3545'];
                header("Location: ".$_SERVER['PHP_SELF']); exit;
            }

            $hash = password_hash($password, PASSWORD_DEFAULT);

            $stmt = $pdo->prepare("
                UPDATE users SET
                username=?, email=?, phone=?, password_hash=?,
                department_id=?, user_role=?, status=?, license_number=?
                WHERE id=? AND facility_id=?
            ");
            $stmt->execute([
                $username,$email,$phone,$hash,
                $dept_id,$role,$status,$license_no,  // ADDED LICENSE NUMBER
                $id,$facility_id
            ]);
        } else {
            $stmt = $pdo->prepare("
                UPDATE users SET
                username=?, email=?, phone=?,
                department_id=?, user_role=?, status=?, license_number=?
                WHERE id=? AND facility_id=?
            ");
            $stmt->execute([
                $username,$email,$phone,
                $dept_id,$role,$status,$license_no,  // ADDED LICENSE NUMBER
                $id,$facility_id
            ]);
        }

        $_SESSION['flash'] = ['message'=>'User updated','color'=>'#007bff'];
        header("Location: ".$_SERVER['PHP_SELF']); exit;
    }

    /* ---------- TOGGLE STATUS ---------- */
    if (isset($_POST['toggle'])) {

        $id     = (int)$_POST['id'];
        $status = $_POST['current_status'] === 'active' ? 'inactive' : 'active';

        $stmt = $pdo->prepare("
            UPDATE users
            SET status=?
            WHERE id=? AND facility_id=?
        ");
        $stmt->execute([$status,$id,$facility_id]);

        $_SESSION['flash'] = [
            'message'=>$status==='active'?'User activated':'User deactivated',
            'color'=>$status==='active'?'#28a745':'#dc3545'
        ];
        header("Location: ".$_SERVER['PHP_SELF']); exit;
    }
}

/* ================= FETCH USERS (FACILITY ONLY) ================= */
$stmt = $pdo->prepare("
    SELECT u.*, d.name AS dept_name
    FROM users u
    LEFT JOIN departments d 
        ON d.id = u.department_id 
       AND d.facility_id = u.facility_id
    WHERE u.facility_id = ?
    ORDER BY u.id ASC
");
$stmt->execute([$facility_id]);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

$currentPage = basename($_SERVER['PHP_SELF']);
?>





<!-- Navbar and Sidebar -->
<nav class="header-navbar navbar navbar-with-menu navbar-fixed-top navbar-semi-dark navbar-shadow">
  <?php include('includes/navbar.php'); ?>
</nav>
<div class="main-menu menu-fixed menu-dark menu-accordion menu-shadow">
  <?php include('includes/sidebar.php'); ?>
</div>

<div class="app-content content container-fluid">
  <div class="content-wrapper">
    <div class="col-xs-12">
      <div class="card">
        <div class="card-header">
          <h4 class="card-title">Users Management</h4>
        </div>
        <div class="card-body collapse in">
          <div class="card-block card-dashboard">
            <div class="row mb-2">
              <div class="col-lg-4 col-md-6 col-sm-12">
                <button type="button" class="btn btn-outline-primary btn-md" data-toggle="modal" data-target="#addUserModal">Add User</button>
              </div>
            </div>

            <div class="table-responsive">
              <table class="table table-hover mb-0" id="Table">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>Role & Username</th>
                    <th>Phone & Email</th>
                    <th>License Number</th> <!-- ADDED LICENSE NUMBER COLUMN -->
                    <th>Department</th>
                    <th>Status</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tbody>
                  <?php $counter=1; foreach($users as $u): ?>
                  <tr>
                    <td><?= $counter++ ?></td>
                    <td>
                      <?= 
                          '<div>' . htmlspecialchars($u['username']) . '</div>'
                          .'<div>' . htmlspecialchars($u['user_role']) . '</div>'
                      ?>
                    </td>
                    <td>
                      <?= 
                          '<div>' . htmlspecialchars($u['phone']) . '</div>'
                          . '<div>' . htmlspecialchars($u['email']) . '</div>'
                      ?>
                    </td>
                    <td>
                      <?= !empty($u['license_number']) 
                          ? htmlspecialchars($u['license_number']) 
                          : '<span class="text-muted">Not provided</span>' 
                      ?>
                    </td> <!-- ADDED LICENSE NUMBER CELL -->
                    <td><?= htmlspecialchars($u['dept_name'] ?? 'Not Assigned') ?></td>

                    <td style="color: <?= $u['status']=='active'?'#28a745':'#dc3545' ?>; font-weight:bold;">
                        <?= ucfirst($u['status']) ?>
                    </td>
                    <td>
                      <button class="btn btn-sm btn-primary" data-toggle="modal" data-target="#editModal<?= $u['id'] ?>">Edit</button>

                      <form method="post" style="display:inline-block">
                        <input type="hidden" name="id" value="<?= $u['id'] ?>">
                        <input type="hidden" name="current_status" value="<?= $u['status'] ?>">
                        <input type="hidden" name="csrf" value="<?= $csrf ?>">
                        <button type="submit" name="toggle" class="btn btn-sm <?= $u['status']=='active'?'btn btn-secondary':'btn btn-success' ?>">
                          <?= $u['status']=='active'?'Deactivate':'Activate' ?>
                        </button>
                      </form>
                    </td>
                  </tr>

                  <!-- Edit Modal -->
                    <div class="modal fade" id="editModal<?= $u['id'] ?>" tabindex="-1">
                      <div class="modal-dialog">
                        <div class="modal-content">
                          <form method="post">
                            <input type="hidden" name="csrf" value="<?= $csrf ?>">
                            <input type="hidden" name="id" value="<?= $u['id'] ?>">
                    
                            <div class="modal-header">
                              <h4>Edit User</h4>
                            </div>
                    
                            <div class="modal-body">
                    
                              <label>Username *</label>
                              <input type="text" name="username"
                                     value="<?= htmlspecialchars($u['username']) ?>"
                                     class="form-control" required>
                    
                              <label>Email *</label>
                              <input type="email" name="email"
                                     value="<?= htmlspecialchars($u['email']) ?>"
                                     class="form-control" required>
                    
                              <label>Phone</label>
                              <input type="text" name="phone"
                                     value="<?= htmlspecialchars($u['phone']) ?>"
                                     class="form-control">
                    
                              <!-- ADDED LICENSE NUMBER FIELD -->
                              <label>License Number (Optional)</label>
                              <input type="text" name="license_number"
                                     value="<?= htmlspecialchars($u['license_number'] ?? '') ?>"
                                     class="form-control"
                                     placeholder="e.g., MED-12345">
                    
                              <label>New Password</label>
                              <div class="input-group">
                                <input type="password" name="password"
                                       id="editPassword<?= $u['id'] ?>" class="form-control">
                                <span class="input-group-append">
                                  <button type="button" class="btn btn-outline-secondary"
                                          onclick="togglePassword('editPassword<?= $u['id'] ?>')">Show</button>
                                </span>
                              </div>
                    
                              <label>Confirm Password</label>
                              <div class="input-group">
                                <input type="password" name="confirm_password"
                                       id="editConfirmPassword<?= $u['id'] ?>" class="form-control">
                                <span class="input-group-append">
                                  <button type="button" class="btn btn-outline-secondary"
                                          onclick="togglePassword('editConfirmPassword<?= $u['id'] ?>')">Show</button>
                                </span>
                              </div>
                    
                              <label>Department</label>
                              <select name="department_id" class="form-control">
                                <option value="">-- Select Department --</option>
                                <?php foreach($departments as $d): ?>
                                  <option value="<?= $d['id'] ?>"
                                    <?= $u['department_id']==$d['id']?'selected':'' ?>>
                                    <?= htmlspecialchars($d['name']) ?>
                                  </option>
                                <?php endforeach; ?>
                              </select>
                    
                              <label>Role *</label>
                              <select name="user_role" class="form-control" required>
                                <?php foreach($userRoles as $role): ?>
                                  <option value="<?= $role ?>"
                                    <?= $u['user_role']==$role?'selected':'' ?>>
                                    <?= $role ?>
                                  </option>
                                <?php endforeach; ?>
                              </select>
                    
                              <label>Status *</label>
                              <select name="status" class="form-control" required>
                                <option value="active" <?= $u['status']=='active'?'selected':'' ?>>Active</option>
                                <option value="inactive" <?= $u['status']=='inactive'?'selected':'' ?>>Inactive</option>
                                <option value="pending" <?= $u['status']=='pending'?'selected':'' ?>>Pending</option>
                              </select>
                    
                            </div>
                    
                            <div class="modal-footer">
                              <button type="submit" name="update"
                                      class="btn btn-outline-primary btn-md">Update</button>
                            </div>
                          </form>
                        </div>
                      </div>
                    </div>


                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Add User Modal -->
<div class="modal fade" id="addUserModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">

      <form method="post" id="addUserForm">
        <input type="hidden" name="csrf" value="<?= $csrf ?>">

        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <label class="modal-title">Add User</label>
        </div>

        <div class="modal-body">

          <label>Username *</label>
          <input type="text" name="username" class="form-control" required>

          <label>Email *</label>
          <input type="email" name="email" class="form-control" required>

          <label>Phone</label>
          <input type="text" name="phone" class="form-control">

          <!-- ADDED LICENSE NUMBER FIELD -->
          <label>License Number (Optional)</label>
          <input type="text" name="license_number" class="form-control"
                 placeholder="e.g., MED-12345">

          <label>Password *</label>
          <div class="input-group">
            <input type="password" name="password"
                   id="addPassword" class="form-control" required>
            <span class="input-group-append">
              <button type="button" class="btn btn-outline-secondary"
                      onclick="togglePassword('addPassword')">Show</button>
            </span>
          </div>

          <label>Confirm Password *</label>
          <div class="input-group">
            <input type="password" name="confirm_password"
                   id="addConfirmPassword" class="form-control" required>
            <span class="input-group-append">
              <button type="button" class="btn btn-outline-secondary"
                      onclick="togglePassword('addConfirmPassword')">Show</button>
            </span>
          </div>

          <label>Department</label>
          <select name="department_id" class="form-control">
            <option value="">-- Select Department --</option>
            <?php foreach($departments as $d): ?>
              <option value="<?= $d['id'] ?>">
                <?= htmlspecialchars($d['name']) ?>
              </option>
            <?php endforeach; ?>
          </select>

          <label>Role *</label>
          <select name="user_role" class="form-control" required>
            <?php foreach($userRoles as $role): ?>
              <option value="<?= $role ?>"><?= $role ?></option>
            <?php endforeach; ?>
          </select>

          <label>Status *</label>
          <select name="status" class="form-control" required>
            <option value="active">Active</option>
            <option value="inactive">Inactive</option>
            <option value="pending">Pending</option>
          </select>

        </div>

        <div class="modal-footer">
          <button type="button"
                  class="btn btn-outline-secondary btn-md"
                  data-dismiss="modal">Close</button>
          <button type="submit"
                  name="create"
                  class="btn btn-outline-primary btn-md">Save</button>
        </div>

      </form>
    </div>
  </div>
</div>


<style>
.toast-message{
  position:fixed;
  top:20px;
  right:20px;
  z-index:9999;
  padding:.75rem 1rem;
  border-radius:.25rem;
  opacity:0.95;
  color: #fff;
  font-weight: 600;
  box-shadow: 0 2px 6px rgba(0,0,0,0.2);
}
</style>

<script>
function togglePassword(id) {
  const input = document.getElementById(id);
  input.type = input.type === "password" ? "text" : "password";
}

// Add User Form validation: password match
document.getElementById('addUserForm')?.addEventListener('submit', function(e){
  const pw = document.getElementById('addPassword').value;
  const cpw = document.getElementById('addConfirmPassword').value;
  if(pw !== cpw){
    alert('Passwords do not match!');
    e.preventDefault();
  }
});
</script>

<?php include('includes/footer.php'); ?>

<?php if(isset($_SESSION['flash'])): ?>
<script>
  window.onload = function() {
    const toast = document.createElement('div');
    toast.className = 'toast-message';
    toast.style.background = '<?= $_SESSION['flash']['color'] ?>';
    toast.innerText = '<?= $_SESSION['flash']['message'] ?>';
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 4000);
  }
</script>
<?php unset($_SESSION['flash']); endif; ?>