<?php
require_once __DIR__ . '/../includes/auth.php';
require_login();

global $con;
if (!isset($con) || !$con) {
  http_response_code(500);
  echo '<!doctype html><html><head><meta charset="utf-8"><title>Server error</title><link rel="stylesheet" href="/adminconsole/assets/ui.css"></head><body><div class="master-wrap"><div class="card"><h2>Server error</h2><div class="alert danger">DB connection not initialized.</div></div></div></body></html>';
  exit;
}

date_default_timezone_set('Asia/Kolkata');

$verifiedProfileType = (int)($verifiedProfileType ?? 0);
if (!in_array($verifiedProfileType, [1, 2], true)) {
  http_response_code(500);
  echo 'Invalid verification page configuration.';
  exit;
}

$verifiedEntityLabel = $verifiedProfileType === 1 ? 'Employer' : 'Jobseeker';
$verifiedEntityPlural = $verifiedProfileType === 1 ? 'Employers' : 'Jobseekers';
$verifiedPageTitle = 'Verified ' . $verifiedEntityPlural;

function vhm_h($s): string
{
  return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
}

function vhm_parse_date($value): ?string
{
  $value = trim((string)$value);
  if ($value === '') return null;
  foreach (['d-m-Y', 'Y-m-d', 'd/m/Y', 'Y-m-d H:i:s'] as $format) {
    $dt = DateTime::createFromFormat($format, $value);
    if ($dt instanceof DateTime) return $dt->format('Y-m-d');
  }
  $ts = strtotime($value);
  return $ts ? date('Y-m-d', $ts) : null;
}

function vhm_fmt_date($date): string
{
  $ts = strtotime((string)$date);
  return $ts ? date('d M y', $ts) : '';
}

function vhm_fmt_dt($date): string
{
  $ts = strtotime((string)$date);
  return $ts ? date('d M Y h:i A', $ts) : '';
}

function vhm_keep_params(array $changes = []): string
{
  $qs = $_GET;
  foreach ($changes as $k => $v) {
    if ($v === null) unset($qs[$k]);
    else $qs[$k] = $v;
  }
  $path = strtok($_SERVER['REQUEST_URI'] ?? '', '?') ?: ($_SERVER['PHP_SELF'] ?? '');
  $q = http_build_query($qs);
  return $q ? $path . '?' . $q : $path;
}

function vhm_table_exists(mysqli $con, string $table): bool
{
  $table = $con->real_escape_string($table);
  $rs = $con->query("SHOW TABLES LIKE '{$table}'");
  return $rs && $rs->num_rows > 0;
}

function vhm_col_exists(mysqli $con, string $table, string $col): bool
{
  $table = $con->real_escape_string($table);
  $col = $con->real_escape_string($col);
  $rs = $con->query("SHOW COLUMNS FROM `{$table}` LIKE '{$col}'");
  return $rs && $rs->num_rows > 0;
}

function vhm_norm_path($path): string
{
  $path = str_replace('\\', '/', (string)$path);
  $path = parse_url($path, PHP_URL_PATH) ?: $path;
  $path = preg_replace('#/+#', '/', $path);
  if ($path === '') $path = '/';
  if ($path[0] !== '/') $path = '/' . $path;
  return rtrim($path, '/') ?: '/';
}

function vhm_acl_allowed(mysqli $con): bool
{
  $me = $_SESSION['admin_user'] ?? [];
  $uid = (int)($me['id'] ?? 0);
  if ($uid <= 0) return false;

  $roleId = (int)($me['role_id'] ?? 0);
  if ($roleId <= 0 && vhm_table_exists($con, 'jos_admin_users_roles')) {
    $st = $con->prepare("SELECT role_id FROM jos_admin_users_roles WHERE user_id=? LIMIT 1");
    if ($st) {
      $st->bind_param('i', $uid);
      $st->execute();
      $roleId = (int)($st->get_result()->fetch_column() ?: 0);
      $st->close();
    }
  }

  $script = vhm_norm_path($_SERVER['SCRIPT_NAME'] ?? '');
  $request = vhm_norm_path($_SERVER['REQUEST_URI'] ?? '');
  $base = basename($script);
  $candidates = array_values(array_unique(array_filter([
    $script,
    $request,
    $base,
    preg_replace('#^/adminconsole#', '', $script),
    preg_replace('#^/adminconsole#', '', $request),
    '/adminconsole/operations/' . $base,
    '/superadmin/' . preg_replace('/\.php$/', '', $base),
  ])));

  if (!vhm_table_exists($con, 'jos_admin_menus')) return true;

  $menuIds = [];
  $menuCanView = false;
  foreach ($candidates as $candidate) {
    $like = '%' . $candidate . '%';
    $st = $con->prepare("SELECT id, can_view FROM jos_admin_menus WHERE menu_link=? OR menu_link LIKE ? LIMIT 5");
    if (!$st) continue;
    $st->bind_param('ss', $candidate, $like);
    $st->execute();
    $rs = $st->get_result();
    while ($row = $rs->fetch_assoc()) {
      $menuIds[] = (int)$row['id'];
      if ((int)($row['can_view'] ?? 0) === 1) $menuCanView = true;
    }
    $st->close();
  }

  $menuIds = array_values(array_unique(array_filter($menuIds)));
  if (!$menuIds) return $roleId === 1;
  if (!vhm_table_exists($con, 'jos_admin_rolemenus') || $roleId <= 0) return $menuCanView;

  $hasCanView = vhm_col_exists($con, 'jos_admin_rolemenus', 'can_view');
  foreach ($menuIds as $menuId) {
    $sql = $hasCanView
      ? "SELECT can_view FROM jos_admin_rolemenus WHERE role_id=? AND menu_id=? LIMIT 1"
      : "SELECT 1 AS can_view FROM jos_admin_rolemenus WHERE role_id=? AND menu_id=? LIMIT 1";
    $st = $con->prepare($sql);
    if (!$st) continue;
    $st->bind_param('ii', $roleId, $menuId);
    $st->execute();
    $canView = $st->get_result()->fetch_column();
    $st->close();
    if ((int)$canView === 1) return true;
  }

  return $menuCanView && $roleId === 1;
}

if (!vhm_acl_allowed($con)) {
  http_response_code(403);
  echo '<!doctype html><html><head><meta charset="utf-8"><title>403 Access denied</title><link rel="stylesheet" href="/adminconsole/assets/ui.css"></head><body><div class="master-wrap" style="padding:40px 0"><div class="card" style="max-width:820px;margin:0 auto"><h2 style="margin-top:0">403 - Access denied</h2><div class="alert danger">You do not have permission to view this page.</div><div style="margin-top:12px"><a class="btn secondary" href="/adminconsole/">Return to dashboard</a></div></div></div></body></html>';
  exit;
}

$search = trim((string)($_GET['q'] ?? ''));

// Show ALL records by default
$from = vhm_parse_date($_GET['from'] ?? ($_POST['from'] ?? '')) ?: '1990-01-01';
$to = vhm_parse_date($_GET['to'] ?? ($_POST['to'] ?? '')) ?: date('Y-m-d');

if ($from > $to) {
  [$from, $to] = [$to, $from];
}
if (isset($_POST['range']) && $_POST['range'] === 'lifetime') {
  $from = '1990-01-01';
  $to = date('Y-m-d');
}
if ($from > $to) [$from, $to] = [$to, $from];

$perPage = max(5, min(100, (int)($_GET['per_page'] ?? 25)));
$page = max(1, (int)($_GET['page'] ?? 1));
$offset = ($page - 1) * $perPage;

$nameExpr = $verifiedProfileType === 1
  ? "COALESCE(NULLIF(rp.organization_name,''), NULLIF(rp.contact_person_name,''), u.mobile_no, CONCAT('User #', u.id))"
  : "COALESCE(NULLIF(cp.candidate_name,''), u.mobile_no, CONCAT('User #', u.id))";
$profileJoin = $verifiedProfileType === 1
  ? "LEFT JOIN jos_app_recruiter_profile rp ON rp.id = u.profile_id"
  : "LEFT JOIN jos_app_candidate_profile cp ON cp.id = u.profile_id";
$searchSql = '';
$params = [$verifiedProfileType, $from, $to];
$types = 'iss';
if ($search !== '') {
  $searchSql = " AND ({$nameExpr} LIKE CONCAT('%',?,'%') OR au.name LIKE CONCAT('%',?,'%') OR u.mobile_no LIKE CONCAT('%',?,'%') OR DATE_FORMAT(u.verified_at, '%d %b %y') LIKE CONCAT('%',?,'%'))";
  array_push($params, $search, $search, $search, $search);
  $types .= 'ssss';
}

$countSql = "SELECT COUNT(*) AS cnt FROM (
  SELECT DATE(u.verified_at) AS verified_date
  FROM jos_app_users u
  {$profileJoin}
  LEFT JOIN jos_admin_users au ON au.id = u.verified_by
  WHERE u.profile_type_id=? AND u.verfied_status=1 AND u.verified_at IS NOT NULL
    AND DATE(u.verified_at) BETWEEN ? AND ? {$searchSql}
  GROUP BY DATE(u.verified_at)
) x";
$st = $con->prepare($countSql);
$st->bind_param($types, ...$params);
$st->execute();
$totalRows = (int)($st->get_result()->fetch_assoc()['cnt'] ?? 0);
$st->close();

$summarySql = "SELECT DATE(u.verified_at) AS verified_date, COUNT(*) AS verified_count
  FROM jos_app_users u
  {$profileJoin}
  LEFT JOIN jos_admin_users au ON au.id = u.verified_by
  WHERE u.profile_type_id=? AND u.verfied_status=1 AND u.verified_at IS NOT NULL
    AND DATE(u.verified_at) BETWEEN ? AND ? {$searchSql}
  GROUP BY DATE(u.verified_at)
  ORDER BY verified_date DESC
  LIMIT ? OFFSET ?";
$summaryParams = $params;
$summaryTypes = $types . 'ii';
$summaryParams[] = $perPage;
$summaryParams[] = $offset;
$st = $con->prepare($summarySql);
$st->bind_param($summaryTypes, ...$summaryParams);
$st->execute();
$summaryRows = $st->get_result()->fetch_all(MYSQLI_ASSOC);
$st->close();

if (isset($_GET['ajax'])) {
  header('Content-Type: application/json; charset=utf-8');
  $date = vhm_parse_date($_GET['date'] ?? '');
  if (!$date) {
    echo json_encode(['ok' => false, 'message' => 'Invalid date.']);
    exit;
  }

  if ($_GET['ajax'] === 'verified_by') {
    $sql = "SELECT COALESCE(NULLIF(au.name,''), CONCAT('Admin #', u.verified_by), 'Unknown') AS verified_by_name,
                   COUNT(*) AS verified_count,
                   MAX(u.verified_at) AS last_verified_at
            FROM jos_app_users u
            LEFT JOIN jos_admin_users au ON au.id = u.verified_by
            WHERE u.profile_type_id=? AND u.verfied_status=1 AND DATE(u.verified_at)=?
            GROUP BY u.verified_by, au.name
            ORDER BY verified_count DESC, verified_by_name ASC";
    $st = $con->prepare($sql);
    $st->bind_param('is', $verifiedProfileType, $date);
    $st->execute();
    $rows = $st->get_result()->fetch_all(MYSQLI_ASSOC);
    $st->close();
    foreach ($rows as &$row) $row['last_verified_at'] = vhm_fmt_dt($row['last_verified_at']);
    echo json_encode(['ok' => true, 'rows' => $rows]);
    exit;
  }

  if ($_GET['ajax'] === 'details') {
    $sql = "SELECT {$nameExpr} AS verified_user,
                   COALESCE(NULLIF(au.name,''), CONCAT('Admin #', u.verified_by), 'Unknown') AS verified_by_name,
                   u.verified_at
            FROM jos_app_users u
            {$profileJoin}
            LEFT JOIN jos_admin_users au ON au.id = u.verified_by
            WHERE u.profile_type_id=? AND u.verfied_status=1 AND DATE(u.verified_at)=?
            ORDER BY u.verified_at ASC, u.id ASC";
    $st = $con->prepare($sql);
    $st->bind_param('is', $verifiedProfileType, $date);
    $st->execute();
    $rows = $st->get_result()->fetch_all(MYSQLI_ASSOC);
    $st->close();
    foreach ($rows as &$row) $row['verified_at'] = vhm_fmt_dt($row['verified_at']);
    echo json_encode(['ok' => true, 'rows' => $rows]);
    exit;
  }

  echo json_encode(['ok' => false, 'message' => 'Invalid action.']);
  exit;
}

$totalPages = max(1, (int)ceil($totalRows / $perPage));
?>
<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?= vhm_h($verifiedPageTitle) ?></title>
  <link rel="stylesheet" href="/adminconsole/assets/ui.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
  <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
  <style>
    .vhm-head {
      display: flex;
      justify-content: space-between;
      gap: 14px;
      align-items: flex-start;
      flex-wrap: wrap;
      margin-bottom: 14px
    }

    .vhm-title {
      font-size: 22px;
      font-weight: 800;
      color: #fff;
      margin: 0
    }

    .vhm-sub {
      color: #9ca3af;
      margin-top: 4px
    }

    .vhm-filter {
      display: flex;
      gap: 8px;
      align-items: flex-end;
      flex-wrap: wrap
    }

    .vhm-filter label {
      display: block;
      font-size: 12px;
      color: #9ca3af;
      margin-bottom: 5px
    }

    .vhm-filter .inp {
      width: 170px
    }

    .vhm-actions {
      display: flex;
      gap: 8px;
      flex-wrap: wrap
    }

    .vhm-empty {
      padding: 36px 16px;
      text-align: center;
      color: #9ca3af
    }

    .vhm-pagination {
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 10px;
      flex-wrap: wrap;
      margin-top: 14px;
      color: #9ca3af
    }

    .vhm-modal {
      position: fixed;
      inset: 0;
      background: rgba(2, 6, 23, .72);
      display: none;
      align-items: center;
      justify-content: center;
      padding: 18px;
      z-index: 50
    }

    .vhm-modal.open {
      display: flex
    }

    .vhm-dialog {
      width: min(920px, 100%);
      max-height: 86vh;
      overflow: auto;
      background: #111827;
      border: 1px solid #374151;
      border-radius: 12px;
      color: #e5e7eb
    }

    .vhm-dialog-head {
      display: flex;
      justify-content: space-between;
      gap: 10px;
      align-items: center;
      padding: 14px 16px;
      border-bottom: 1px solid #1f2937
    }

    .vhm-dialog-title {
      font-weight: 800;
      color: #fff
    }

    .vhm-dialog-body {
      padding: 14px 16px
    }

    .vhm-close {
      width: 36px;
      height: 36px;
      border-radius: 8px;
      border: 1px solid #374151;
      background: #1f2937;
      color: #fff;
      cursor: pointer;
      font-size: 20px;
      line-height: 1
    }

    .vhm-loader {
      padding: 28px;
      text-align: center;
      color: #9ca3af
    }

    @media (max-width:760px) {

      .vhm-filter,
      .vhm-filter .inp,
      .vhm-filter .btn {
        width: 100%
      }

      .vhm-actions .btn {
        width: 100%;
        text-align: center
      }

      th,
      td {
        white-space: nowrap
      }
    }
  </style>
</head>

<body>
  <div class="master-wrap">
    <div class="card">
      <div class="vhm-head">
        <div>
          <h1 class="vhm-title"><?= vhm_h($verifiedPageTitle) ?></h1>
          <div class="vhm-sub">Daily verified <?= vhm_h(strtolower($verifiedEntityPlural)) ?> grouped by verification date.</div>
        </div>
        <form method="get" class="vhm-filter">
          <div><label>Search</label><input class="inp" type="text" name="q" value="<?= vhm_h($search) ?>" placeholder="Name, admin, mobile"></div>
          <div><label>From</label><input placeholder="DD-MM-YYYY" class="inp flatpickr-date" type="text" name="from" value="<?= vhm_h($from) ?>"></div>
          <div><label>To</label><input placeholder="DD-MM-YYYY" class="inp flatpickr-date" type="text" name="to" value="<?= vhm_h($to) ?>"></div>
          <div>
            <label>Per page</label>
            <select class="inp small" name="per_page">
              <?php foreach ([10, 25, 50, 100] as $n): ?>
                <option value="<?= $n ?>" <?= $perPage === $n ? 'selected' : '' ?>><?= $n ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <button class="btn primary" type="submit">Apply</button>
          <a class="btn secondary" href="<?= vhm_h(strtok($_SERVER['REQUEST_URI'] ?? '', '?') ?: $_SERVER['PHP_SELF']) ?>">Reset</a>
        </form>
      </div>

      <div class="table-wrap">
        <table>
          <thead>
            <tr>
              <th>Sr. No.</th>
              <th>Date</th>
              <th>Day</th>
              <th>Verified Counts</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            <?php if ($summaryRows): ?>
              <?php foreach ($summaryRows as $i => $row):
                $date = (string)$row['verified_date'];
                $sr = $offset + $i + 1;
              ?>
                <tr>
                  <td><?= $sr ?></td>
                  <td><?= vhm_h(vhm_fmt_date($date)) ?></td>
                  <td><?= vhm_h(date('l', strtotime($date))) ?></td>
                  <td><?= (int)$row['verified_count'] ?></td>
                  <td>
                    <div class="vhm-actions">
                      <button type="button" class="btn secondary" data-modal="verified_by" data-date="<?= vhm_h($date) ?>" data-label="<?= vhm_h(vhm_fmt_date($date)) ?>">Verified By </button>
                      <button type="button" class="btn primary" data-modal="details" data-date="<?= vhm_h($date) ?>" data-label="<?= vhm_h(vhm_fmt_date($date)) ?>">View Verified <?= vhm_h($verifiedEntityPlural) ?>
                      </button>
                    </div>
                  </td>
                </tr>
              <?php endforeach; ?>
            <?php else: ?>
              <tr>
                <td colspan="5">
                  <div class="vhm-empty">No verified <?= vhm_h(strtolower($verifiedEntityPlural)) ?> found for the selected filters.</div>
                </td>
              </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>

      <div class="vhm-pagination">
        <div>Showing <?= $totalRows ? ($offset + 1) : 0 ?>-<?= min($offset + $perPage, $totalRows) ?> of <?= $totalRows ?> day(s)</div>
        <div class="vhm-actions">
          <a class="btn secondary" href="<?= vhm_h(vhm_keep_params(['page' => max(1, $page - 1)])) ?>" <?= $page <= 1 ? 'style="pointer-events:none;opacity:.45"' : '' ?>>Previous</a>
          <span>Page <?= $page ?> of <?= $totalPages ?></span>
          <a class="btn secondary" href="<?= vhm_h(vhm_keep_params(['page' => min($totalPages, $page + 1)])) ?>" <?= $page >= $totalPages ? 'style="pointer-events:none;opacity:.45"' : '' ?>>Next</a>
        </div>
      </div>
    </div>
  </div>

  <div id="vhmModal" class="vhm-modal" role="dialog" aria-modal="true" aria-hidden="true">
    <div class="vhm-dialog">
      <div class="vhm-dialog-head">
        <div class="vhm-dialog-title" id="vhmModalTitle">Details</div>
        <button type="button" class="vhm-close" id="vhmClose" aria-label="Close">&times;</button>
      </div>
      <div class="vhm-dialog-body" id="vhmModalBody">
        <div class="vhm-loader">Loading...</div>
      </div>
    </div>
  </div>

  <script>
    (function() {
      var modal = document.getElementById('vhmModal'),
        title = document.getElementById('vhmModalTitle'),
        body = document.getElementById('vhmModalBody'),
        closeBtn = document.getElementById('vhmClose');
      var entity = <?= json_encode($verifiedEntityLabel) ?>;

      function esc(v) {
        return String(v == null ? '' : v).replace(/[&<>"']/g, function(c) {
          return {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
          } [c];
        });
      }

      function openModal() {
        modal.classList.add('open');
        modal.setAttribute('aria-hidden', 'false');
      }

      function closeModal() {
        modal.classList.remove('open');
        modal.setAttribute('aria-hidden', 'true');
      }

      function empty(text) {
        body.innerHTML = '<div class="vhm-empty">' + esc(text) + '</div>';
      }

      function renderVerifiedBy(rows) {
        if (!rows.length) return empty('No verifier records found.');
        var html = '<div class="table-wrap"><table><thead><tr><th>Sr.No</th><th>Verified By</th><th>Verified Counts</th><th>Last Verified At</th></tr></thead><tbody>';
        rows.forEach(function(r, i) {
          html += '<tr><td>' + (i + 1) + '</td><td>' + esc(r.verified_by_name) + '</td><td>' + esc(r.verified_count) + '</td><td>' + esc(r.last_verified_at) + '</td></tr>';
        });
        body.innerHTML = html + '</tbody></table></div>';
      }

      function renderDetails(rows) {
        if (!rows.length) return empty('No verified ' + entity.toLowerCase() + ' records found.');
        var html = '<div class="table-wrap"><table><thead><tr><th>Sr.No</th><th>Verified User</th><th>Verified By</th><th>Verified At</th></tr></thead><tbody>';
        rows.forEach(function(r, i) {
          html += '<tr><td>' + (i + 1) + '</td><td>' + esc(r.verified_user) + '</td><td>' + esc(r.verified_by_name) + '</td><td>' + esc(r.verified_at) + '</td></tr>';
        });
        body.innerHTML = html + '</tbody></table></div>';
      }

      function load(type, date, label) {
        title.textContent = (type === 'verified_by' ? 'Verified By' : 'Verified ' + entity + ' Users') + ' - ' + label;
        body.innerHTML = '<div class="vhm-loader">Loading...</div>';
        openModal();
        var url = new URL(window.location.href);
        url.searchParams.set('ajax', type);
        url.searchParams.set('date', date);
        fetch(url.toString(), {
          headers: {
            'X-Requested-With': 'XMLHttpRequest'
          }
        }).then(function(r) {
          return r.json();
        }).then(function(data) {
          if (!data.ok) return empty(data.message || 'Unable to load details.');
          if (type === 'verified_by') renderVerifiedBy(data.rows || []);
          else renderDetails(data.rows || []);
        }).catch(function() {
          empty('Unable to load details. Please try again.');
        });
      }
      document.addEventListener('click', function(e) {
        var btn = e.target.closest('[data-modal]');
        if (btn) load(btn.getAttribute('data-modal'), btn.getAttribute('data-date'), btn.getAttribute('data-label'));
      });
      closeBtn.addEventListener('click', closeModal);
      modal.addEventListener('click', function(e) {
        if (e.target === modal) closeModal();
      });
      document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') closeModal();
      });
    })();

    flatpickr(".flatpickr-date", {
      altInput: true, // user sees formatted date
      altFormat: "d-m-Y", // display format
      dateFormat: "Y-m-d", // value sent to backend
      allowInput: false,
      maxDate: "today"
    });
  </script>
</body>

</html>