<?php
session_start();
if (!isset($_SESSION['admin'])) {
  echo "<script>document.location.href='logout.php';</script>";
  exit;
}

require_once '../core/conn.php';

/** Admin */
$rs = mysqli_query($con, "SELECT id, username FROM admin WHERE id=".(int)$_SESSION['admin']." LIMIT 1");
$admin = ($rs && mysqli_num_rows($rs)) ? mysqli_fetch_assoc($rs) : ['id'=>0,'username'=>'Admin'];

/** Users (Verified) */
$users = [];
$q = mysqli_query($con, "SELECT company_name, branch, name, username, email, phone, state, lga, address, photo, type, status
                         FROM users
                         WHERE status='1'
                         ORDER BY username ASC");
if ($q) while ($u = mysqli_fetch_assoc($q)) $users[] = $u;

/** Staff/User types from upgrade table */
$types = [];
$tq = mysqli_query($con, "SELECT DISTINCT type FROM upgrade WHERE type IS NOT NULL AND type<>'' ORDER BY type ASC");
if ($tq) while ($r = mysqli_fetch_assoc($tq)) $types[] = trim($r['type']);
if (empty($types)) $types = ['STAFF']; // fallback

/** Header (your layout/home.css) */
require_once 'include/header.php';
?>

<!-- ✅ Bootstrap + DataTables CSS (ONLY for forms/modals/table polish) -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/v/bs4/dt-1.13.8/datatables.min.css">

<!-- (Optional) tiny bridge to make Bootstrap form controls blend with your UI -->
<style>
  /* don’t touch your home.css — just make bootstrap forms sit nicely */
  .modal-content { border-radius: 18px; overflow: hidden; }
  .modal-header { background: #f7fbff; border-bottom: 1px solid rgba(15,23,42,.08); }
  .modal-title { font-weight: 900; color: #0b2a66; }
  .form-control { border-radius: 14px; }
  .btn { border-radius: 14px; font-weight: 800; }
</style>

<div class="main">
  <div class="content">

    <div class="page-title">
      <div>
        <h2>Verified Users</h2>
        <p>Hello, <?= htmlspecialchars($admin['username']) ?> — welcome back</p>
      </div>

      <div class="actions">
        <button type="button" class="btnx primary" data-toggle="modal" data-target="#modalAddUser">
          ➕ Add User
        </button>
      </div>
    </div>

    <div class="card">
      <div class="head">
        <h3>Users List</h3>
        <div class="tools">
          <input type="text" id="searchGlobal" class="inp" placeholder="Search any field…">
          <input type="text" id="searchUsername" class="inp" placeholder="Search by username…">
        </div>
      </div>

      <div class="body">
        <div class="tablewrap">
          <table id="usersTable" class="table table-striped table-hover" style="width:100%">
            <thead>
              <tr>
                <th>S/N</th>
                <th>Company</th>
                <th>Branch</th>
                <th>Name</th>
                <th>Username</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Type</th>
                <th>State</th>
                <th>LGA</th>
                <th>Status</th>
                <th style="width:170px">Action</th>
              </tr>
            </thead>
            <tbody>
              <?php if (!empty($users)): ?>
                <?php $sn=1; foreach($users as $u): ?>
                  <tr>
                    <td><?= $sn++ ?></td>
                    <td><?= htmlspecialchars($u['company_name'] ?? '') ?></td>
                    <td><?= htmlspecialchars($u['branch'] ?? '') ?></td>
                    <td><?= htmlspecialchars($u['name'] ?? '') ?></td>
                    <td><?= htmlspecialchars($u['username'] ?? '') ?></td>
                    <td><?= htmlspecialchars($u['email'] ?? '') ?></td>
                    <td><?= htmlspecialchars($u['phone'] ?? '') ?></td>
                    <td><?= htmlspecialchars($u['type'] ?? '') ?></td>
                    <td><?= htmlspecialchars($u['state'] ?? '') ?></td>
                    <td><?= htmlspecialchars($u['lga'] ?? '') ?></td>
                    <td><span class="badge b-ok">Verified</span></td>
                    <td>
                      <button class="btn btn-sm btn-info" type="button"
                              onclick="openUserModal('<?= htmlspecialchars($u['username'], ENT_QUOTES) ?>')">
                        View
                      </button>
                      <button class="btn btn-sm btn-warning" type="button"
                              onclick="banUser('<?= htmlspecialchars($u['username'], ENT_QUOTES) ?>')">
                        Ban
                      </button>
                      <button class="btn btn-sm btn-secondary" type="button"
                              onclick="unverifyUser('<?= htmlspecialchars($u['username'], ENT_QUOTES) ?>')">
                        Unverify
                      </button>
                      <button class="btn btn-sm btn-danger" type="button"
                              onclick="deleteUser('<?= htmlspecialchars($u['username'], ENT_QUOTES) ?>')">
                        Delete
                      </button>
                    </td>
                  </tr>
                <?php endforeach; ?>
              <?php else: ?>
                <tr><td colspan="12" class="text-center font-weight-bold">No verified users yet.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

  </div>
</div>


<!-- ===================== ADD USER MODAL ===================== -->
<div class="modal fade" id="modalAddUser" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <form id="formAddUser" onsubmit="return false;">
        <div class="modal-header">
          <h3 class="modal-title">Create User</h3>
          <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
        </div>

        <div class="modal-body">

          <div class="form-group">
            <label>Company Name</label>
            <input type="text" class="form-control" id="company_name" required>
          </div>

          <div class="form-group">
            <label>Branch</label>
            <input type="text" class="form-control" id="branch" required>
          </div>

          <div class="form-group">
            <label>Full Name</label>
            <input type="text" class="form-control" id="name" required>
          </div>

          <div class="form-group">
            <label>Username</label>
            <input type="text" class="form-control" id="username" required>
          </div>

          <div class="form-group">
            <label>Email</label>
            <input type="email" class="form-control" id="email">
          </div>

          <div class="form-group">
            <label>Phone (11 digits)</label>
            <input type="tel" class="form-control" id="phone" maxlength="11" required>
          </div>

          <div class="form-group">
            <label>State</label>
            <input type="text" class="form-control" id="state">
          </div>

          <div class="form-group">
            <label>LGA</label>
            <input type="text" class="form-control" id="lga">
          </div>

          <div class="form-group">
            <label>Address</label>
            <input type="text" class="form-control" id="address">
          </div>

          <div class="form-group">
            <label>User Type (from Upgrade table)</label>
            <select class="form-control" id="type" required>
              <?php foreach($types as $tp): ?>
                <option value="<?= htmlspecialchars($tp) ?>"><?= htmlspecialchars($tp) ?></option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="form-group">
            <label>Password</label>
            <input type="password" class="form-control" id="password" required>
          </div>

          <div class="form-group">
            <label>Status</label>
            <select class="form-control" id="status">
              <option value="1" selected>Active / Verified</option>
              <option value="0">Unverified</option>
              <option value="2">Banned</option>
            </select>
          </div>

        </div>

        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary" id="btnSubmitAdd">Submit</button>
        </div>
      </form>
    </div>
  </div>
</div>


<!-- ===================== EDIT USER MODAL ===================== -->
<div class="modal fade" id="modalEditUser" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <form id="formEditUser" onsubmit="return false;">
        <div class="modal-header">
          <h5 class="modal-title">User Details</h5>
          <button type="button" class="close" data-dismiss="modal"><span>×</span></button>
        </div>

        <div class="modal-body">
          <div class="row">
            <div class="col-md-6 form-group">
              <label>Company</label>
              <input type="text" class="form-control" id="ud_company">
            </div>
            <div class="col-md-6 form-group">
              <label>Branch</label>
              <input type="text" class="form-control" id="ud_branch">
            </div>
            <div class="col-md-6 form-group">
              <label>Full Name</label>
              <input type="text" class="form-control" id="ud_name" required>
            </div>
            <div class="col-md-6 form-group">
              <label>Username</label>
              <input type="text" class="form-control" id="ud_username" required>
            </div>
            <div class="col-md-6 form-group">
              <label>Email</label>
              <input type="email" class="form-control" id="ud_email">
            </div>
            <div class="col-md-6 form-group">
              <label>Phone</label>
              <input type="text" class="form-control" id="ud_phone">
            </div>
            <div class="col-md-6 form-group">
              <label>Type (from Upgrade table)</label>
              <select class="form-control" id="ud_type" required>
                <?php foreach($types as $tp): ?>
                  <option value="<?= htmlspecialchars($tp) ?>"><?= htmlspecialchars($tp) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6 form-group">
              <label>Status</label>
              <select class="form-control" id="ud_status">
                <option value="1">Active</option>
                <option value="0">Unverified</option>
                <option value="2">Banned</option>
              </select>
            </div>
            <div class="col-md-12 form-group">
              <label>New Password (optional)</label>
              <input type="password" class="form-control" id="ud_new_password" placeholder="Leave blank to keep old">
            </div>
          </div>

          <input type="hidden" id="ud_original_username">
        </div>

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


<!-- ✅ Required JS for Bootstrap modal + DataTables -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.2/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/v/bs4/dt-1.13.8/datatables.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/gasparesganga-jquery-loading-overlay@2.1.7/dist/loadingoverlay.min.js"></script>

<script>
/* =================== HELPERS =================== */
function showLoad(on){ try{ on ? $.LoadingOverlay("show") : $.LoadingOverlay("hide"); }catch(e){} }
function okResp(res){ return !!res && (res.success === true || String(res.status) === '200'); }

function postAction(action, data, cb){
  data = data || {};
  data.action = action;
  $.ajax({
    type:'POST',
    url:'../assets/users_action.php',
    data:data,
    dataType:'json',
    beforeSend: ()=>showLoad(true),
    complete: ()=>showLoad(false),
    success: (res)=>cb && cb(res),
    error: (xhr)=>{ console.error(xhr.responseText); swal("Error","Server error.","error"); }
  });
}

$(function(){
  let dt = $('#usersTable').DataTable({ pageLength: 25 });
  $('#searchGlobal').on('keyup change', function(){ dt.search(this.value).draw(); });
  $('#searchUsername').on('keyup change', function(){ dt.column(4).search(this.value).draw(); });
});

/* =================== ADD USER =================== */
$('#btnSubmitAdd').on('click', ()=> $('#formAddUser').trigger('submit'));

$('#formAddUser').on('submit', function(e){
  e.preventDefault();

  let data = {
    company_name: $('#company_name').val().trim(),
    branch: $('#branch').val().trim(),
    name: $('#name').val().trim(),
    username: $('#username').val().trim(),
    email: $('#email').val().trim(),
    phone: $('#phone').val().trim(),
    state: $('#state').val().trim(),
    lga: $('#lga').val().trim(),
    address: $('#address').val().trim(),
    type: $('#type').val().trim(),
    password: $('#password').val(),
    status: $('#status').val()
  };

  if(!data.company_name || !data.branch || !data.name || !data.username || !data.phone || !data.password || !data.type){
    return swal("Incomplete","Please fill all required fields.","error");
  }
  if(!/^\d{11}$/.test(data.phone)){
    return swal("Invalid phone","Phone must be 11 digits.","error");
  }

  swal({
    title: "Dear <?= htmlspecialchars($admin['username']) ?>",
    text: "Create user: " + data.name + " ?",
    icon: "warning",
    buttons: true,
    dangerMode: true
  }).then(function(ok){
    if(!ok) return;
    postAction('create', data, function(res){
      if(okResp(res)){
        swal("Created", "User created successfully.", "success").then(()=>location.reload());
      }else{
        swal("Error", res.message || "Failed to create user.", "error");
      }
    });
  });
});

/* =================== OPEN EDIT MODAL =================== */
window.openUserModal = function(username){
  postAction('get', { username: username }, function(res){
    if(!okResp(res) || !res.data){
      return swal("Error", res.message || "Unable to load user.", "error");
    }
    let u = res.data;
    $('#ud_company').val(u.company_name || '');
    $('#ud_branch').val(u.branch || '');
    $('#ud_name').val(u.name || '');
    $('#ud_username').val(u.username || '');
    $('#ud_email').val(u.email || '');
    $('#ud_phone').val(u.phone || '');
    $('#ud_type').val(u.type || '');
    $('#ud_status').val(String(u.status));
    $('#ud_original_username').val(u.username || '');
    $('#ud_new_password').val('');
    $('#modalEditUser').modal('show');
  });
};

/* =================== SAVE EDIT =================== */
$('#formEditUser').on('submit', function(e){
  e.preventDefault();

  let data = {
    original_username: $('#ud_original_username').val(),
    company_name: $('#ud_company').val().trim(),
    branch: $('#ud_branch').val().trim(),
    name: $('#ud_name').val().trim(),
    username: $('#ud_username').val().trim(),
    email: $('#ud_email').val().trim(),
    phone: $('#ud_phone').val().trim(),
    type: $('#ud_type').val().trim(),
    status: $('#ud_status').val(),
    new_password: $('#ud_new_password').val()
  };

  postAction('update', data, function(res){
    if(okResp(res)){
      swal("Saved","User updated successfully.","success").then(()=>location.reload());
    }else{
      swal("Error", res.message || "Failed to update user.", "error");
    }
  });
});

/* =================== ACTIONS =================== */
function actionAsk(action, username, label){
  swal({
    title: "Dear <?= htmlspecialchars($admin['username']) ?>",
    text: "Are you sure you want to " + label + " " + username + " ?",
    icon: "warning",
    buttons: true,
    dangerMode: true
  }).then(function(ok){
    if(!ok) return;
    postAction(action, { username: username }, function(res){
      if(okResp(res)){
        swal("Done","Action completed.","success").then(()=>location.reload());
      }else{
        swal("Error", res.message || "Action failed.", "error");
      }
    });
  });
}
window.banUser = (u)=> actionAsk('ban', u, 'ban');
window.unverifyUser = (u)=> actionAsk('unverify', u, 'unverify');
window.deleteUser = (u)=> actionAsk('delete', u, 'delete');
</script>
