<?php
@session_start();
session_start();
error_reporting(0);
include('config.php');

require_once ('auth_guard.php');

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

// Simple CSRF
if (empty($_SESSION['csrf'])) { $_SESSION['csrf'] = bin2hex(random_bytes(32)); }
function csrf_input(){ echo '<input type="hidden" name="csrf" value="'.h($_SESSION['csrf']).'">'; }
function csrf_check($t){ return isset($_SESSION['csrf']) && hash_equals($_SESSION['csrf'], $t ?? ''); }

// ---------- Activate / Deactivate ----------
if (isset($_GET['inid'])) {
    $id = $_GET['inid'];
    $stmt = $conn->prepare("UPDATE aspnetusers SET email_confirmed=0 WHERE id=:id");
    $stmt->execute([':id'=>$id]);
    header('Location: user_list.php'); exit;
}
if (isset($_GET['id'])) {
    $id = $_GET['id'];
    $stmt = $conn->prepare("UPDATE aspnetusers SET email_confirmed=1 WHERE id=:id");
    $stmt->execute([':id'=>$id]);
    header('Location: user_list.php'); exit;
}

// ---------- Handle Profile Update (all except email) ----------
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['update_user'])) {
    if (!csrf_check($_POST['csrf'] ?? '')) {
        $_SESSION['flash'] = ['type'=>'error','msg'=>'Invalid session token. Please retry.'];
        header('Location: user_list.php'); exit;
    }

    $id = (int)($_POST['id'] ?? 0);
    if ($id <= 0) { $_SESSION['flash']=['type'=>'error','msg'=>'Invalid user.']; header('Location: user_list.php'); exit; }

    // Whitelist of editable columns (EMAIL EXCLUDED ON PURPOSE)
    $allowed = [
        '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,
        'wallet_address' => PDO::PARAM_STR,

        // Employment
        'education' => PDO::PARAM_STR,
        'employee_status' => PDO::PARAM_STR,
        'industry' => PDO::PARAM_STR,

        // Trading Experience
        'forex_exp' => PDO::PARAM_STR,
        'other'     => PDO::PARAM_STR,

        // Investment
        'investment_plan'    => PDO::PARAM_STR,
        'investment_purpose' => PDO::PARAM_STR,

        // Login (do NOT touch email)
        'password' => PDO::PARAM_STR,
    ];

    // Build dynamic SET ...
    $sets = [];
    $params = [':id' => $id];
    foreach ($allowed as $col => $type) {
        if (array_key_exists($col, $_POST)) {
            $sets[] = "`$col` = :$col";
            $params[":$col"] = $_POST[$col];
        }
    }

    if ($sets) {
        $sql = "UPDATE aspnetusers SET ".implode(', ', $sets)." WHERE id = :id";
        $stmt = $conn->prepare($sql);
        foreach ($params as $k=>$v) {
            $paramType = ($k!==':id') ? $allowed[ltrim($k,':')] ?? PDO::PARAM_STR : PDO::PARAM_INT;
            $stmt->bindValue($k, $v, $paramType);
        }
        $stmt->execute();
        $_SESSION['flash']=['type'=>'success','msg'=>'Profile updated.'];
    } else {
        $_SESSION['flash']=['type'=>'info','msg'=>'No changes to save.'];
    }

    header('Location: user_list.php'); exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Clients List</title>

  <!-- Tailwind -->
  <script src="https://cdn.tailwindcss.com"></script>

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

  <!-- Bootstrap 4.6 (for modals & tabs) -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"/>

  <!-- DataTables core + Responsive extension -->
  <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"/>

  <style>
    .badge { display:inline-block; padding:0.35em 0.65em; font-size:.75em; font-weight:700; line-height:1; border-radius:.25rem; }
    .badge-success { color:#fff; background:#db6612; }
    .badge-danger  { color:#fff; background:#dc3545; }
    .badge-primary { color:#fff; background:#db6612; }
    .card { box-shadow:0 4px 6px -1px rgba(0,0,0,.1), 0 2px 4px -1px rgba(0,0,0,.06); border-radius:.5rem; }
    .btn { transition:all .3s ease; }
    .btn:hover { transform:translateY(-1px); box-shadow:0 4px 6px rgba(0,0,0,.1); background:#db6612;}
    @media (max-width:768px){
      .table-responsive { overflow-x:auto; -webkit-overflow-scrolling:touch; }
    }
    table.dataTable thead th { background:#f9fafb; }
  </style>
</head>
<body class="bg-gray-100">
<?php include('header.php');?>

<div class="flex flex-col md:flex-row h-screen">
  <!-- Sidebar -->
  <?php include "side_bar.php";?>

  <main class="flex-1 p-4 md:p-6 md:ml-64">
    <div class="container mx-auto">
      <!-- Header -->
      <div class="flex flex-col md:flex-row justify-between items-center mb-6">
        <h1 class="text-2xl font-bold text-gray-800 mb-4 md:mb-0">Clients List</h1>
        <a href="dashboard.php" class="bg-[#FF6B00] hover:bg-[#E55F00] text-white font-medium py-2 px-6 rounded-full transition duration-300 shadow-md">
          <i class="fas fa-arrow-left mr-2"></i>Back to Dashboard
        </a>
      </div>

      <?php if (!empty($_SESSION['flash'])): $f=$_SESSION['flash']; unset($_SESSION['flash']); ?>
        <div class="mb-4 rounded-md p-3 text-sm <?= $f['type']==='success' ? 'bg-green-50 text-green-700 border border-green-200' : ($f['type']==='error' ? 'bg-rose-50 text-rose-700 border border-rose-200' : 'bg-orange-50 text-orange-700 border border-orange-200') ?>">
          <?= h($f['msg']) ?>
        </div>
      <?php endif; ?>

      <!-- Table -->
      <div class="bg-white rounded-xl shadow-md overflow-hidden">
        <div class="p-4">
          <div class="table-responsive">
            <table id="depositTable" class="display nowrap w-full">
              <thead class="bg-gray-50">
                <tr>
                  <th>Name</th>
                  <th>Email</th>
                  <th>Country</th>
                  <th>Number</th>
                  <th>Status</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody class="bg-white divide-y divide-gray-200">
              <?php
              $sql = "SELECT * FROM aspnetusers";
              $query = $conn->prepare($sql);
              $query->execute();
              $results = $query->fetchAll(PDO::FETCH_OBJ);

              if ($query->rowCount() > 0) {
                foreach ($results as $row) {
                  // Unique suffix
                  $uidSource = $row->id ?? $row->email ?? uniqid('u_');
                  $uid = preg_replace('/[^a-zA-Z0-9_]/', '_', (string)$uidSource);

                  $status = (string)$row->email_confirmed === '1' ? 'Active' : 'Inactive';
                  $badgeClass = (string)$row->email_confirmed === '1' ? 'badge-success' : 'badge-danger';

                  // Safe values
                  $id       = (int)($row->id ?? 0);
                  $fullname = h($row->fullname ?? '');
                  $email    = h($row->email ?? '');
                  $password = h($row->password ?? '');
                  $country  = h($row->country ?? '');
                  $number   = h($row->number ?? '');
                  $dial     = h($row->dial_code ?? '');
                  $state    = h($row->state ?? '');
                  $city     = h($row->city ?? '');
                  $zip      = h($row->zipcode ?? '');
                  $address  = h($row->address ?? '');
                  $gender   = h($row->gender ?? '');
                  $aboutme  = h($row->aboutme ?? '');
                  $reg_date = h($row->reg_date ?? '');
                  $wallet   = h($row->wallet_address ?? '');

                  $education = h($row->education ?? '');
                  $employee_status = h($row->employee_status ?? '');
                  $industry  = h($row->industry ?? '');

                  $forex_exp = h($row->forex_exp ?? '');
                  $other     = h($row->other ?? '');

                  $investment_plan    = h($row->investment_plan ?? '');
                  $investment_purpose = h($row->investment_purpose ?? '');
                  ?>
                  <tr>
                    <td><div><?= $fullname ?></div></td>
                    <td><div class="amount"><?= $email ?></div></td>
                    <td><div><?= $country ?></div></td>
                    <td><div><?= $number ?></div></td>
                    <td><span class="badge <?= $badgeClass ?>"><?= $status ?></span></td>
                    <td class="whitespace-nowrap">
                      <?php if ((string)$row->email_confirmed === '1') { ?>
                        <a href="user_list.php?inid=<?= urlencode((string)($row->id ?? '')) ?>"
                           onclick="return confirm('Do you want to Deactivate this client?');"
                           class="btn btn-danger btn-sm m-1" title="Inactive this client">
                          <i class="fa fa-unlock"></i>
                        </a>
                      <?php } else { ?>
                        <a href="user_list.php?id=<?= urlencode((string)($row->id ?? '')) ?>"
                           onclick="return confirm('Do you want to Activate this client?');"
                           class="btn btn-primary btn-sm m-1" title="Active this client">
                          <i class="fa fa-lock"></i>
                        </a>
                      <?php } ?>

                      <a href="https://test.traderssolution.com/crmvideonew/login.php?email=<?= urlencode((string)$row->email) ?>&password=<?= urlencode((string)$row->password) ?>"
                         class="btn btn-success btn-sm m-1"
                         title="Login as Client">
                         Login
                      </a>

                      <!-- View/Edit Details trigger -->
                      <button type="button"
                              class="btn btn-success btn-sm m-1"
                              data-toggle="modal"
                              data-target="#profile_<?= $uid ?>">
                        View Details
                      </button>
<style>
    .nav-link active{
        background-color:#db6612;
    }
</style>
                      <!-- Profile Modal (Edit Form) -->
                      <div class="modal fade" id="profile_<?= $uid ?>" tabindex="-1" role="dialog" aria-labelledby="profileLabel_<?= $uid ?>" aria-hidden="true" style="margin-top:40px;">
                        <div class="modal-dialog modal-lg" role="document">
                          <div class="modal-content">
                            <form method="post" action="user_list.php" autocomplete="off">
                              <?php csrf_input(); ?>
                              <input type="hidden" name="update_user" value="1">
                              <input type="hidden" name="id" value="<?= (int)$row->id ?>">
                              <div class="modal-header" style="box-shadow:0 4px 8px rgba(0,0,0,.08);padding:15px;">
                                <h4 class="modal-title" id="profileLabel_<?= $uid ?>" style="padding-left:20px;color:#f12126">Client Details</h4>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                  <span aria-hidden="true">&times;</span>
                                </button>
                              </div>
                              <div class="modal-body">
                                <!-- Tabs -->
                                <ul class="nav nav-pills nav-pills-custom" id="pills-tab-custom-<?= $uid ?>" role="tablist" style="background-color:#f8f9fa;box-shadow:0 4px 8px rgba(0,0,0,.08);">
                                  <li class="nav-item">
                                    <a class="nav-link active" id="pills-health-tab-<?= $uid ?>" data-toggle="pill" href="#pills-health-<?= $uid ?>" role="tab" aria-controls="pills-health-<?= $uid ?>" aria-selected="true">
                                      Personal Data
                                    </a>
                                  </li>
                                  <li class="nav-item">
                                    <a class="nav-link" id="pills-career-tab-<?= $uid ?>" data-toggle="pill" href="#pills-career-<?= $uid ?>" role="tab" aria-controls="pills-career-<?= $uid ?>" aria-selected="false">
                                      Employment
                                    </a>
                                  </li>
                                  <li class="nav-item">
                                    <a class="nav-link" id="pills-trade-tab-<?= $uid ?>" data-toggle="pill" href="#pills-trade-<?= $uid ?>" role="tab" aria-controls="pills-trade-<?= $uid ?>" aria-selected="false">
                                      Trading Experience
                                    </a>
                                  </li>
                                  <li class="nav-item">
                                    <a class="nav-link" id="pills-invest-tab-<?= $uid ?>" data-toggle="pill" href="#pills-invest-<?= $uid ?>" role="tab" aria-controls="pills-invest-<?= $uid ?>" aria-selected="false">
                                      Investment
                                    </a>
                                  </li>
                                  <li class="nav-item">
                                    <a class="nav-link" id="pills-login-tab-<?= $uid ?>" data-toggle="pill" href="#pills-login-<?= $uid ?>" role="tab" aria-controls="pills-login-<?= $uid ?>" aria-selected="false">
                                      Login
                                    </a>
                                  </li>
                                </ul>

                                <br>

                                <div class="tab-content" id="pills-tabContent-<?= $uid ?>">
                                  <!-- Personal Data -->
                                  <div class="tab-pane fade show active" id="pills-health-<?= $uid ?>" role="tabpanel" aria-labelledby="pills-health-tab-<?= $uid ?>">
                                    <div class="row">
                                      <div class="col-md-6 grid-margin stretch-card">
                                        <div class="card"><div class="card-body">
                                          <div class="form-group">
                                            <label>Wallet ID</label>
                                            <input type="text" class="form-control" name="wallet_address" value="<?= $wallet ?>">
                                          </div>
                                          <div class="form-group">
                                            <label>Full Name</label>
                                            <input type="text" class="form-control" name="fullname" value="<?= $fullname ?>">
                                          </div>
                                          <div class="form-group">
                                            <label>Email (read-only)</label>
                                            <input type="email" class="form-control" value="<?= $email ?>" readonly>
                                          </div>
                                          <div class="form-group">
                                            <label>Country</label>
                                            <input type="text" class="form-control" name="country" value="<?= $country ?>">
                                          </div>
                                          <div class="form-group">
                                            <label>Dial Code</label>
                                            <input type="text" class="form-control" name="dial_code" value="<?= $dial ?>">
                                          </div>
                                          <div class="form-group">
                                            <label>Mobile No</label>
                                            <input type="text" class="form-control" name="number" value="<?= $number ?>">
                                          </div>
                                          <div class="form-group">
                                            <label>State</label>
                                            <input type="text" class="form-control" name="state" value="<?= $state ?>">
                                          </div>
                                        </div></div>
                                      </div>
                                      <div class="col-md-6 grid-margin stretch-card">
                                        <div class="card"><div class="card-body">
                                          <div class="form-group">
                                            <label>City</label>
                                            <input type="text" class="form-control" name="city" value="<?= $city ?>">
                                          </div>
                                          <div class="form-group">
                                            <label>Zipcode</label>
                                            <input type="text" class="form-control" name="zipcode" value="<?= $zip ?>">
                                          </div>
                                          <div class="form-group">
                                            <label>Address</label>
                                            <input type="text" class="form-control" name="address" value="<?= $address ?>">
                                          </div>
                                          <div class="form-group">
                                            <label>Gender</label>
                                            <input type="text" class="form-control" name="gender" value="<?= $gender ?>">
                                          </div>
                                          <div class="form-group">
                                            <label>About me</label>
                                            <textarea class="form-control" rows="4" name="aboutme"><?= $aboutme ?></textarea>
                                          </div>
                                          <div class="form-group">
                                            <label>Reg Date</label>
                                            <input type="text" class="form-control" value="<?= $reg_date ?>" readonly>
                                          </div>
                                        </div></div>
                                      </div>
                                    </div>
                                  </div>

                                  <!-- Employment -->
                                  <div class="tab-pane fade" id="pills-career-<?= $uid ?>" role="tabpanel" aria-labelledby="pills-career-tab-<?= $uid ?>">
                                    <div class="row">
                                      <div class="col-md-4 grid-margin stretch-card">
                                        <div class="card"><div class="card-body">
                                          <div class="form-group">
                                            <label>Education</label>
                                            <input type="text" class="form-control" name="education" value="<?= $education ?>">
                                          </div>
                                        </div></div>
                                      </div>
                                      <div class="col-md-4 grid-margin stretch-card">
                                        <div class="card"><div class="card-body">
                                          <div class="form-group">
                                            <label>Employment Status</label>
                                            <input type="text" class="form-control" name="employee_status" value="<?= $employee_status ?>">
                                          </div>
                                        </div></div>
                                      </div>
                                      <div class="col-md-4 grid-margin stretch-card">
                                        <div class="card"><div class="card-body">
                                          <div class="form-group">
                                            <label>Industry</label>
                                            <input type="text" class="form-control" name="industry" value="<?= $industry ?>">
                                          </div>
                                        </div></div>
                                      </div>
                                    </div>
                                  </div>

                                  <!-- Trading Experience -->
                                  <div class="tab-pane fade" id="pills-trade-<?= $uid ?>" role="tabpanel" aria-labelledby="pills-trade-tab-<?= $uid ?>">
                                    <div class="row">
                                      <div class="col-md-4 grid-margin stretch-card">
                                        <div class="card"><div class="card-body">
                                          <div class="form-group">
                                            <label>Forex</label>
                                            <input type="text" class="form-control" name="forex_exp" value="<?= $forex_exp ?>">
                                          </div>
                                        </div></div>
                                      </div>
                                      <div class="col-md-4 grid-margin stretch-card">
                                        <div class="card"><div class="card-body">
                                          <div class="form-group">
                                            <label>CFDs on Futures</label>
                                            <input type="text" class="form-control" name="cfd" value="<?= h($row->cfd ?? '') ?>">
                                          </div>
                                        </div></div>
                                      </div>
                                      <div class="col-md-4 grid-margin stretch-card">
                                        <div class="card"><div class="card-body">
                                          <div class="form-group">
                                            <label>Other Derivatives</label>
                                            <input type="text" class="form-control" name="other" value="<?= $other ?>">
                                          </div>
                                        </div></div>
                                      </div>
                                    </div>
                                  </div>

                                  <!-- Investment -->
                                  <div class="tab-pane fade" id="pills-invest-<?= $uid ?>" role="tabpanel" aria-labelledby="pills-invest-tab-<?= $uid ?>">
                                    <div class="row">
                                      <div class="col-md-6 grid-margin stretch-card">
                                        <div class="card"><div class="card-body">
                                          <div class="form-group">
                                            <label>Planned Investment</label>
                                            <input type="text" class="form-control" name="investment_plan" value="<?= $investment_plan ?>">
                                          </div>
                                        </div></div>
                                      </div>
                                      <div class="col-md-6 grid-margin stretch-card">
                                        <div class="card"><div class="card-body">
                                          <div class="form-group">
                                            <label>Purpose of Investing</label>
                                            <input type="text" class="form-control" name="investment_purpose" value="<?= $investment_purpose ?>">
                                          </div>
                                        </div></div>
                                      </div>
                                    </div>
                                  </div>

                                  <!-- Login -->
                                  <div class="tab-pane fade" id="pills-login-<?= $uid ?>" role="tabpanel" aria-labelledby="pills-login-tab-<?= $uid ?>">
                                    <div class="row">
                                      <div class="col-md-6 grid-margin stretch-card">
                                        <div class="card"><div class="card-body">
                                          <div class="form-group">
                                            <label>Username</label>
                                            <input type="text" class="form-control" value="<?= $email ?>" readonly>
                                          </div>
                                        </div></div>
                                      </div>
                                      <div class="col-md-6 grid-margin stretch-card">
                                        <div class="card"><div class="card-body">
                                          <div class="form-group">
                                            <label>Password</label>
                                            <input type="text" class="form-control" name="password" value="<?= $password ?>">
                                          </div>
                                        </div></div>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                <!-- /tab content -->
                              </div>
                              <div class="modal-footer">
                                <button type="button" class="btn btn-light" data-dismiss="modal">Close</button>
                                <button type="submit" class="btn btn-primary">Save Changes</button>
                              </div>
                            </form>
                          </div>
                        </div>
                      </div>
                      <!-- /Profile Modal -->
                    </td>
                  </tr>
                  <?php
                }
              }
              ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

    </div>
  </main>
</div>

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

<!-- jQuery first, then Bootstrap (for modals), then DataTables -->
<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.8/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>

<script>
  $(function () {
    const dt = $('#depositTable').DataTable({
      responsive: true,
      autoWidth: false,
      pageLength: 25,
      order: [[0, 'asc']],
      columnDefs: [
        { orderable: false, targets: [5] }
      ],
      language: {
        search: "_INPUT_",
        searchPlaceholder: "Search clients...",
        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" }
      }
    });

    $('.dataTables_filter input')
      .addClass('border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring w-56');
    $('.dataTables_length select')
      .addClass('border border-gray-300 rounded-md px-2 py-1');
  });
</script>
</body>
</html>
