<?php
session_start();
error_reporting(0);
require_once 'config.php'; // must define $conn (PDO)

// OPTIONAL auth check
// if (empty($_SESSION['role']) || $_SESSION['role'] !== 'admin') { header('Location: login.php'); exit; }

header('X-Content-Type-Options: nosniff');

// ---------- AJAX: UPDATE USER ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['ajax'] ?? '') === 'update_user') {
    header('Content-Type: application/json; charset=utf-8');
    try {
        $id = (int)($_POST['id'] ?? 0);
        if ($id <= 0) { echo json_encode(['ok'=>false,'error'=>'Invalid user id']); exit; }

        // Allowed fields to update
        $fields = [
            'email'=>PDO::PARAM_STR, 'username'=>PDO::PARAM_STR, 'fullname'=>PDO::PARAM_STR,
            'country'=>PDO::PARAM_STR, 'dial_code'=>PDO::PARAM_STR, 'number'=>PDO::PARAM_STR,
            'state'=>PDO::PARAM_STR, 'city'=>PDO::PARAM_STR, 'zipcode'=>PDO::PARAM_STR,
            'address'=>PDO::PARAM_STR, 'gender'=>PDO::PARAM_STR, 'aboutme'=>PDO::PARAM_STR,
            'education'=>PDO::PARAM_STR, 'employee_status'=>PDO::PARAM_STR, 'industry'=>PDO::PARAM_STR,
            'forex_exp'=>PDO::PARAM_STR, 'other'=>PDO::PARAM_STR, 'investment_plan'=>PDO::PARAM_STR,
            'investment_purpose'=>PDO::PARAM_STR, 'wallet_address'=>PDO::PARAM_STR,
            'email_confirmed'=>PDO::PARAM_INT, 'number_confirmed'=>PDO::PARAM_INT,
            'two_factor_enabled'=>PDO::PARAM_INT, 'lockout_enabled'=>PDO::PARAM_INT,
            'status'=>PDO::PARAM_INT, 'kyc_verify'=>PDO::PARAM_INT, 'client_status'=>PDO::PARAM_INT,
            'bank_status'=>PDO::PARAM_INT, 'personal_status'=>PDO::PARAM_INT,
            'employemnet_status'=>PDO::PARAM_INT, 'trading_status'=>PDO::PARAM_INT,
        ];

        $set = []; $params = [':id'=>$id];
        foreach ($fields as $name=>$type) {
            if (array_key_exists($name, $_POST)) {
                $set[] = "$name = :$name";
                $params[":$name"] = ($type===PDO::PARAM_INT) ? (int)$_POST[$name] : (string)$_POST[$name];
            }
        }

        // Password: only if provided (non-empty)
        $new_password = trim((string)($_POST['password'] ?? ''));
        if ($new_password !== '') {
            $set[] = "password = :password";
            // NOTE: currently stores plain text to match your schema.
            // If you want hashing, replace with: password_hash($new_password, PASSWORD_DEFAULT)
            $params[':password'] = $new_password;
        }

        if (!$set) { echo json_encode(['ok'=>false,'error'=>'Nothing to update']); exit; }

        $sql = "UPDATE aspnetusers SET ".implode(', ',$set)." WHERE id = :id";
        $stmt = $conn->prepare($sql);
        foreach ($params as $k=>$v) $stmt->bindValue($k,$v);
        $stmt->execute();

        echo json_encode(['ok'=>true]);
    } catch (Throwable $e) {
        echo json_encode(['ok'=>false,'error'=>$e->getMessage()]);
    }
    exit;
}

// ---------- Helper ----------
function h($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

// ---------- Fetch users ----------
$users = [];
try {
    $q = $conn->query("SELECT * FROM aspnetusers ORDER BY id DESC");
    $users = $q->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $errFetch = $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Users & Password Manager</title>

  <!-- Tailwind + jQuery -->
  <script src="https://cdn.tailwindcss.com"></script>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

  <!-- DataTables -->
  <link rel="stylesheet" href="https://cdn.datatables.net/1.13.8/css/jquery.dataTables.min.css"/>
  <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.dataTables.min.css"/>
  <script src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>

  <style>
    :root{
      --brand:#CD7F32; --brand-600:#B76E2B; --ink:#1f2937; --muted:#6b7280;
      --surface:#ffffff; --bg:#f6f7fb; --border:#e5e7eb; --shadow:0 10px 30px rgba(0,0,0,.07);
    }
    body.bg-gray-100{ background:var(--bg)!important; color:var(--ink); }

    /* layout */
    @media (min-width:768px){ main.md\:ml-64{ margin-left:16rem!important; } }
    .container-card{ background:var(--surface); border:1px solid var(--border); border-radius:18px; box-shadow:var(--shadow); }

    /* toolbar */
    .toolbar{ display:flex; gap:.75rem; align-items:center; justify-content:space-between; padding:14px 16px; border-bottom:1px solid var(--border); }
    .toolbar-title{ font-weight:800; letter-spacing:.2px; }
    .search-wrap{ position:relative; width:100%; max-width:360px; }
    .search-input{ width:100%; border:1px solid var(--border); border-radius:12px; padding:.65rem .9rem .65rem 2.25rem; outline:none; background:#fff; }
    .search-input:focus{ border-color:var(--brand); box-shadow:0 0 0 3px rgba(205,127,50,.18); }
    .search-ico{ position:absolute; left:10px; top:50%; transform:translateY(-50%); color:#9ca3af; }

    /* table */
    .table-wrap{ overflow:auto; }
    table.dataTable thead th{ background:linear-gradient(180deg, var(--brand), var(--brand-600)); color:#fff; border:0!important; }
    table.dataTable tbody td{ border-bottom:1px solid var(--border)!important; }
    .dataTables_wrapper .dataTables_filter{ display:none; } /* hide default search */
    .dataTables_wrapper .dataTables_length{ margin:10px 14px; }
    table.dataTable.display tbody tr:nth-child(even){ background:#fffdf8; }
    table.dataTable.display tbody tr:hover{ background:#FFF6EC; }

    /* badges */
    .badge{ display:inline-flex; align-items:center; padding:.25rem .5rem; border-radius:.5rem; font-size:.72rem; font-weight:700; }
    .badge-green{ background:#ecfdf5; color:#047857; border:1px solid #d1fae5; }
    .badge-red{ background:#fef2f2; color:#b91c1c; border:1px solid #fee2e2; }

    /* show/hide pass */
    .toggle-pass{ color:#2563eb; }
    .toggle-pass:hover{ text-decoration:underline; }

   
    /* buttons */
    .btn{ display:inline-flex; align-items:center; justify-content:center; gap:.4rem; border-radius:12px; padding:.55rem .9rem; font-weight:700; }
    .btn-amber{ background:var(--brand); color:#fff; }
    .btn-amber:hover{ background:var(--brand-600); }
    .btn-light{ background:#fff; border:1px solid var(--border); }
  </style>
  <style>/* Overlay: hidden by default */
.modal-overlay{
  position: fixed;
  inset: 0;
  background: rgba(0,0,0,.5);
  display: none;               /* stays hidden until we add .is-open */
  z-index: 5000;
}

/* When open: center horizontally, offset from top */
.modal-overlay.is-open{
  display: flex;
  justify-content: center;     /* center horizontally */
  align-items: flex-start;     /* start at top */
  padding-top: 7vh;            /* gap from top (adjust as you like) */
}

/* Modal panel */
.modal{margin-top:40px;
  max-height: calc(100vh - 12vh);  /* leave room top/bottom */
  overflow-y: auto;
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0,0,0,.07);
  transform: translateY(-6px);
  opacity: 0;
  transition: transform .18s ease, opacity .18s ease;
}

/* Subtle slide-in */
.modal-overlay.is-open .modal{
  transform: translateY(0);
  opacity: 1;
}

/* Optional: slightly less top gap on very small screens */
@media (max-width: 480px){
  .modal-overlay.is-open{ padding-top: 5vh; }
}
</style>
</head>
<body class="bg-gray-100">
<?php include "header.php"; ?>
<div class="flex flex-col md:flex-row h-screen">
  <?php include "side_bar.php"; ?>

  <main class="flex-1 p-6 md:ml-64">
    <div class="container mx-auto">
      <div class="container-card">
        <!-- Toolbar -->
        <div class="toolbar">
          <div class="flex items-center gap-2">
            <span class="inline-flex h-9 w-9 items-center justify-center rounded-xl text-white" style="background:linear-gradient(135deg,var(--brand),var(--brand-600)); box-shadow:0 6px 18px rgba(205,127,50,.25);">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M3 13h8V3H3v10zm0 8h8v-6H3v6zm10 0h8V11h-8v10zm0-18v6h8V3h-8z"></path></svg>
            </span>
            <h2 class="toolbar-title text-xl sm:text-2xl">Users & Password Manager</h2>
          </div>

          <!-- Custom LIVE search -->
          <div class="search-wrap">
            <svg class="search-ico" width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M15.5 14h-.79l-.28-.27A6.471 6.471 0 0 0 16 9.5 6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zM9.5 14A4.5 4.5 0 1 1 14 9.5 4.505 4.505 0 0 1 9.5 14z"/></svg>
            <input id="globalSearch" type="text" class="search-input" placeholder="Search users (name, email, country, etc.)…" autocomplete="off">
          </div>
        </div>

        <!-- Table -->
        <div class="p-3 sm:p-4">
          <?php if (!empty($errFetch)): ?>
            <div class="p-4 mb-4 bg-red-100 text-red-700 rounded">Error: <?= h($errFetch) ?></div>
          <?php endif; ?>

          <div class="table-wrap">
            <table id="usersTable" class="display nowrap w-full">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>Full Name</th>
                  <th>Email (Username)</th>
                  <th>Number</th>
                  <th>Country</th>
                  <th>Status</th>
                  <th>Password</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
              <?php foreach ($users as $u):
                $id = (int)$u['id'];
                $maskId = 'passmask_'.$id;
                $realPass = (string)($u['password'] ?? '');
                $masked   = $realPass !== '' ? str_repeat('•', max(6, strlen($realPass))) : '';
                $statusBadge = ((int)$u['email_confirmed'] === 1)
                  ? '<span class="badge badge-green">Active</span>'
                  : '<span class="badge badge-red">Inactive</span>';
                $b64 = base64_encode(json_encode($u, JSON_UNESCAPED_UNICODE));
              ?>
                <tr>
                  <td><?= $id ?></td>
                  <td><?= h($u['fullname']) ?></td>
                  <td><?= h($u['email']) ?></td>
                  <td><?= h(($u['dial_code']??'').' '.($u['number']??'')) ?></td>
                  <td><?= h($u['country']) ?></td>
                  <td><?= $statusBadge ?></td>
                  <td>
                    <span id="<?= $maskId ?>" class="password-mask" data-pass="<?= h($realPass) ?>"><?= h($masked) ?></span>
                    <?php if ($realPass !== ''): ?>
                      <button type="button" class="ml-2 text-xs toggle-pass" data-mask="#<?= $maskId ?>">Show</button>
                    <?php endif; ?>
                  </td>
                  <td>
                    <button type="button" class="editUser btn btn-amber text-sm" data-user-b64="<?= h($b64) ?>">Edit</button>
                  </td>
                </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <!-- Edit Modal -->
    <div id="editModal" class="modal-overlay">
      <div class="modal bg-white w-full max-w-5xl p-6 relative">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-xl font-semibold">Edit User</h3>
          <button id="closeModal" class="text-gray-500 hover:text-gray-700 text-2xl leading-none">&times;</button>
        </div>

        <form id="editForm" class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <input type="hidden" name="id" id="u_id">
          <input type="hidden" name="ajax" value="update_user">

          <!-- Left -->
          <div class="space-y-3">
            <div><label class="block text-sm text-gray-700">Full Name</label><input class="w-full border rounded p-2" name="fullname" id="u_fullname"></div>
            <div><label class="block text-sm text-gray-700">Email</label><input class="w-full border rounded p-2" name="email" id="u_email"></div>
            <div><label class="block text-sm text-gray-700">Username</label><input class="w-full border rounded p-2" name="username" id="u_username"></div>
            <div class="grid grid-cols-3 gap-2">
              <div><label class="block text-sm text-gray-700">Dial</label><input class="w-full border rounded p-2" name="dial_code" id="u_dial_code"></div>
              <div class="col-span-2"><label class="block text-sm text-gray-700">Number</label><input class="w-full border rounded p-2" name="number" id="u_number"></div>
            </div>
            <div><label class="block text-sm text-gray-700">Country</label><input class="w-full border rounded p-2" name="country" id="u_country"></div>
            <div class="grid grid-cols-2 gap-2">
              <div><label class="block text-sm text-gray-700">State</label><input class="w-full border rounded p-2" name="state" id="u_state"></div>
              <div><label class="block text-sm text-gray-700">City</label><input class="w-full border rounded p-2" name="city" id="u_city"></div>
            </div>
            <div class="grid grid-cols-2 gap-2">
              <div><label class="block text-sm text-gray-700">Zipcode</label><input class="w-full border rounded p-2" name="zipcode" id="u_zipcode"></div>
              <div><label class="block text-sm text-gray-700">Gender</label><input class="w-full border rounded p-2" name="gender" id="u_gender"></div>
            </div>
            <div><label class="block text-sm text-gray-700">Address</label><input class="w-full border rounded p-2" name="address" id="u_address"></div>
            <div><label class="block text-sm text-gray-700">About me</label><textarea class="w-full border rounded p-2" name="aboutme" id="u_aboutme" rows="3"></textarea></div>
          </div>

          <!-- Right -->
          <div class="space-y-3">
            <div class="grid grid-cols-2 gap-2">
              <div><label class="block text-sm text-gray-700">Education</label><input class="w-full border rounded p-2" name="education" id="u_education"></div>
              <div><label class="block text-sm text-gray-700">Employment Status</label><input class="w-full border rounded p-2" name="employee_status" id="u_employee_status"></div>
            </div>
            <div><label class="block text-sm text-gray-700">Industry</label><input class="w-full border rounded p-2" name="industry" id="u_industry"></div>
            <div class="grid grid-cols-2 gap-2">
              <div><label class="block text-sm text-gray-700">Forex Exp</label><input class="w-full border rounded p-2" name="forex_exp" id="u_forex_exp"></div>
              <div><label class="block text-sm text-gray-700">Other Derivatives</label><input class="w-full border rounded p-2" name="other" id="u_other"></div>
            </div>
            <div class="grid grid-cols-2 gap-2">
              <div><label class="block text-sm text-gray-700">Investment Plan</label><input class="w-full border rounded p-2" name="investment_plan" id="u_investment_plan"></div>
              <div><label class="block text-sm text-gray-700">Investment Purpose</label><input class="w-full border rounded p-2" name="investment_purpose" id="u_investment_purpose"></div>
            </div>
            <div><label class="block text-sm text-gray-700">Wallet Address</label><input class="w-full border rounded p-2" name="wallet_address" id="u_wallet_address"></div>

            <div class="grid grid-cols-3 gap-2">
              <div><label class="block text-sm text-gray-700">Email Confirmed</label><select class="w-full border rounded p-2" name="email_confirmed" id="u_email_confirmed"><option value="1">1</option><option value="0">0</option></select></div>
              <div><label class="block text-sm text-gray-700">Number Confirmed</label><select class="w-full border rounded p-2" name="number_confirmed" id="u_number_confirmed"><option value="1">1</option><option value="0">0</option></select></div>
              <div><label class="block text-sm text-gray-700">2FA Enabled</label><select class="w-full border rounded p-2" name="two_factor_enabled" id="u_two_factor_enabled"><option value="1">1</option><option value="0">0</option></select></div>
            </div>

            <div class="grid grid-cols-3 gap-2">
              <div><label class="block text-sm text-gray-700">Lockout Enabled</label><select class="w-full border rounded p-2" name="lockout_enabled" id="u_lockout_enabled"><option value="1">1</option><option value="0">0</option></select></div>
              <div><label class="block text-sm text-gray-700">Client Status</label><select class="w-full border rounded p-2" name="client_status" id="u_client_status"><option value="1">1</option><option value="0">0</option></select></div>
              <div><label class="block text-sm text-gray-700">KYC Verify</label><select class="w-full border rounded p-2" name="kyc_verify" id="u_kyc_verify"><option value="1">1</option><option value="0">0</option></select></div>
            </div>

            <div class="grid grid-cols-3 gap-2">
              <div><label class="block text-sm text-gray-700">Bank Status</label><select class="w-full border rounded p-2" name="bank_status" id="u_bank_status"><option value="1">1</option><option value="0">0</option></select></div>
              <div><label class="block text-sm text-gray-700">Personal Status</label><select class="w-full border rounded p-2" name="personal_status" id="u_personal_status"><option value="1">1</option><option value="0">0</option></select></div>
              <div><label class="block text-sm text-gray-700">Employment Status Flag</label><select class="w-full border rounded p-2" name="employemnet_status" id="u_employemnet_status"><option value="1">1</option><option value="0">0</option></select></div>
            </div>

            <div class="grid grid-cols-2 gap-2">
              <div><label class="block text-sm text-gray-700">Trading Status</label><select class="w-full border rounded p-2" name="trading_status" id="u_trading_status"><option value="1">1</option><option value="0">0</option></select></div>
              <div><label class="block text-sm text-gray-700">Overall Status</label><select class="w-full border rounded p-2" name="status" id="u_status"><option value="1">1</option><option value="0">0</option></select></div>
            </div>

            <div class="pt-2 border-t">
              <label class="block text-sm text-gray-700">New Password (leave blank to keep unchanged)</label>
              <input class="w-full border rounded p-2" type="text" name="password" id="u_password" placeholder="Type new password to change">
            </div>
          </div>

          <div class="md:col-span-2 flex justify-end gap-2 pt-2">
            <button type="button" id="cancelEdit" class="btn btn-light">Cancel</button>
            <button type="submit" class="btn btn-amber">Save Changes</button>
          </div>
        </form>
      </div>
    </div>
    <!-- /Edit Modal -->

  </main>
</div>

<?php include "footer.php"; ?>

<script>
(function($){
  // DataTable init
  let dt;
  if ($.fn.DataTable) {
    dt = $('#usersTable').DataTable({
      responsive: true,
      autoWidth: false,
      pageLength: 25,
      order: [[0, 'desc']],
      columnDefs: [{ orderable:false, targets:[7] }],
      language: {
        search: "_INPUT_", searchPlaceholder: "Search users...",
        lengthMenu: "Show _MENU_ entries",
        info: "Showing _START_ to _END_ of _TOTAL_ entries",
        infoEmpty: "Showing 0 to 0 of 0 entries",
        infoFiltered: "(filtered from _MAX_ total entries)",
        paginate: { first:"First", last:"Last", next:"Next", previous:"Previous" }
      }
    });

    // Our custom LIVE search input controls DataTables filter
    const $s = $('#globalSearch');
    $s.on('input', function(){
      dt.search(this.value).draw();
    });
  }

  // SHOW/HIDE PASSWORD — robust to responsive rows
  $(document).on('click', '.toggle-pass', function(){
    const $btn = $(this);
    const targetSel = $btn.attr('data-mask');
    const $span = $(targetSel);
    if (!$span.length) return;
    const actual = $span.attr('data-pass') || '';
    if ($btn.text() === 'Show') {
      $span.text(actual);
      $btn.text('Hide');
    } else {
      const masked = actual ? '•'.repeat(Math.max(6, (actual+'').length)) : '';
      $span.text(masked);
      $btn.text('Show');
    }
  });

  // Modal helpers
  // Modal helpers
const $modal = $('#editModal');
const openModal  = () => { $modal.addClass('is-open').fadeIn(120); };
const closeModal = () => { $modal.fadeOut(120, () => $modal.removeClass('is-open')); };

$('#closeModal, #cancelEdit').on('click', closeModal);
$(document).on('keydown', e => { if (e.key === 'Escape') closeModal(); });
$modal.on('click', function(e){ if (e.target === this) closeModal(); });


  // OPEN EDIT — base64 JSON + delegated handler
  $(document).on('click', '.editUser', function(){
    const b64 = $(this).attr('data-user-b64') || '';
    let data = {};
    try {
      data = b64 ? JSON.parse(atob(b64)) : {};
    } catch (e) {
      try { data = JSON.parse(atob((b64||'').replace(/&quot;/g,'"'))); } catch (e2) { data = {}; }
    }

    // Populate fields
    $('#u_id').val(data.id || '');
    $('#u_fullname').val(data.fullname || '');
    $('#u_email').val(data.email || '');
    $('#u_username').val(data.username || '');
    $('#u_dial_code').val(data.dial_code || '');
    $('#u_number').val(data.number || '');
    $('#u_country').val(data.country || '');
    $('#u_state').val(data.state || '');
    $('#u_city').val(data.city || '');
    $('#u_zipcode').val(data.zipcode || '');
    $('#u_gender').val(data.gender || '');
    $('#u_address').val(data.address || '');
    $('#u_aboutme').val(data.aboutme || '');

    $('#u_education').val(data.education || '');
    $('#u_employee_status').val(data.employee_status || '');
    $('#u_industry').val(data.industry || '');
    $('#u_forex_exp').val(data.forex_exp || '');
    $('#u_other').val(data.other || '');
    $('#u_investment_plan').val(data.investment_plan || '');
    $('#u_investment_purpose').val(data.investment_purpose || '');
    $('#u_wallet_address').val(data.wallet_address || '');

    $('#u_email_confirmed').val((data.email_confirmed|0));
    $('#u_number_confirmed').val((data.number_confirmed|0));
    $('#u_two_factor_enabled').val((data.two_factor_enabled|0));
    $('#u_lockout_enabled').val((data.lockout_enabled|0));
    $('#u_client_status').val((data.client_status|0));
    $('#u_kyc_verify').val((data.kyc_verify|0));
    $('#u_bank_status').val((data.bank_status|0));
    $('#u_personal_status').val((data.personal_status|0));
    $('#u_employemnet_status').val((data.employemnet_status|0)); // matches DB column name
    $('#u_trading_status').val((data.trading_status|0));
    $('#u_status').val((data.status|0));

    $('#u_password').val(''); // leave blank => unchanged
    openModal();
  });

  // SUBMIT EDIT (AJAX)
  $('#editForm').on('submit', function(e){
    e.preventDefault();
    const $btns = $('#editForm button');
    $btns.prop('disabled', true);
    $.ajax({
      url: '',
      method: 'POST',
      data: $(this).serialize(),
      dataType: 'json'
    }).done(res => {
      if (res && res.ok) {
        location.reload();
      } else {
        alert('Update failed: ' + (res && res.error ? res.error : 'Unknown error'));
      }
    }).fail(xhr => {
      alert('Request failed: ' + xhr.status + ' ' + xhr.statusText);
    }).always(() => $btns.prop('disabled', false));
  });
})(jQuery);
</script>
</body>
</html>
