<?php
/* ======================================================================
   Applications Activity Report
   Source: jos_app_applicationactionlog
   ====================================================================== */
@ini_set('display_errors', '1');
@error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_OFF);

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

$me = $_SESSION['admin_user'] ?? [];
$MY_ID = (int)($me['id'] ?? 0);
$MY_ROLE_ID = isset($me['role_id']) ? (int)$me['role_id'] : 0;
global $con;
if (!$con) {
  die('DB connection not initialized');
}
if (!defined('DOMAIN_URL')) define('DOMAIN_URL', '/');

if (!function_exists('pacific_norm_path')) {
  function pacific_norm_path(string $p): string
  {
    $p = str_replace(["\r", "\n", "\t"], '', $p);
    $p = str_replace('\\', '/', $p);
    $p = preg_replace('#\s+#', '', $p);
    $p = preg_replace('#/+#', '/', $p);
    $p = ltrim($p, '/');
    return strtolower($p);
  }
}
if (!function_exists('pacific_current_role_id')) {
  function pacific_current_role_id(mysqli $con): ?int
  {
    if (function_exists('current_user')) {
      $u = current_user();
      $uid = isset($u['id']) ? (int)$u['id'] : 0;
      if (!empty($u['role_id'])) return (int)$u['role_id'];
      if ($uid > 0) {
        $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();
          $st->bind_result($rid);
          if ($st->fetch()) {
            $st->close();
            return (int)$rid;
          }
          $st->close();
        }
      }
    }
    return null;
  }
}
if (!function_exists('pacific_menu_id_for_path')) {
  function pacific_menu_id_for_path(mysqli $con): ?int
  {
    $qid = isset($_GET['menu_id']) ? (int)$_GET['menu_id'] : 0;
    if ($qid > 0) return $qid;

    $script = $_SERVER['SCRIPT_NAME'] ?? $_SERVER['PHP_SELF'] ?? '';
    $full   = pacific_norm_path($script);
    $nopref = preg_replace('#^adminconsole/#', '', $full);
    $base   = basename($full);
    $stem   = preg_replace('/\.php$/i', '', $base);
    $cands = array_unique(array_filter([$full, $nopref, "adminconsole/$nopref", $base, $stem]));

    $rs = $con->prepare("SELECT id, menu_link FROM jos_admin_menus WHERE status=1");
    if (!$rs) return null;
    $rs->execute();
    $rows = stmt_fetch_all_assoc($rs);
    $rs->close();
    foreach ($rows as $r) {
      $ml = pacific_norm_path((string)$r['menu_link']);
      foreach ($cands as $candRaw) {
        $cand = pacific_norm_path($candRaw);
        if ($ml === $cand || ($cand !== '' && str_ends_with($ml, $cand)) || ($base && str_ends_with($ml, strtolower($base))) || ($stem && str_contains($ml, '/' . $stem))) {
          return (int)$r['id'];
        }
      }
    }
    return null;
  }
}
if (!function_exists('pacific_can_view_this_page')) {
  function pacific_can_view_this_page(mysqli $con): bool
  {
    $rid = pacific_current_role_id($con);
    $mid = pacific_menu_id_for_path($con);
    if (!$rid || !$mid) return false;
    $st = $con->prepare("SELECT can_view FROM jos_admin_rolemenus WHERE role_id=? AND menu_id=? AND (status IS NULL OR status=1) LIMIT 1");
    if (!$st) return false;
    $st->bind_param('ii', $rid, $mid);
    $st->execute();
    $st->bind_result($cv);
    $ok = ($st->fetch() && (int)$cv === 1);
    $st->close();
    return $ok;
  }
}

function h($s)
{
  return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
}
function get_str($k, $d = '')
{
  return isset($_GET[$k]) ? trim((string)$_GET[$k]) : $d;
}
function get_int($k, $d = 0)
{
  return isset($_GET[$k]) ? (int)$_GET[$k] : $d;
}
function fmt_date($s)
{
  return $s ? date('d M Y', strtotime($s)) : '';
}
function fmt_time($s)
{
  return $s ? date('h:i A', strtotime($s)) : '';
}
function normalize_date($s)
{
  $s = trim((string)$s);
  if ($s === '') return '';
  foreach (['Y-m-d', 'd-m-Y', 'd/m/Y'] as $fmt) {
    $d = DateTime::createFromFormat($fmt, $s);
    if ($d) return $d->format('Y-m-d');
  }
  return '';
}
function keep_params(array $changes = [])
{
  $qs = $_GET;
  foreach ($changes as $k => $v) {
    if ($v === null) unset($qs[$k]);
    else $qs[$k] = $v;
  }
  $q = http_build_query($qs);
  return $q ? ('?' . $q) : '';
}
function base_back_to_list()
{
  return h(keep_params(['mode' => null, 'id' => null]));
}
function stmt_fetch_all_assoc(mysqli_stmt $stmt)
{
  $meta = $stmt->result_metadata();
  if (!$meta) return [];
  $out = [];
  $fields = [];
  $row = [];
  $bind = [];
  while ($f = $meta->fetch_field()) {
    $fields[] = $f->name;
    $row[$f->name] = null;
    $bind[] = &$row[$f->name];
  }
  call_user_func_array([$stmt, 'bind_result'], $bind);
  while ($stmt->fetch()) {
    $copy = [];
    foreach ($fields as $f) $copy[$f] = $row[$f];
    $out[] = $copy;
  }
  return $out;
}
function stmt_fetch_one_assoc(mysqli_stmt $stmt)
{
  $rows = stmt_fetch_all_assoc($stmt);
  return $rows ? $rows[0] : null;
}
function bind_params(mysqli_stmt $stmt, string $types, array $params)
{
  if ($types === '') return;
  $refs = [];
  foreach ($params as $k => $v) $refs[$k] = &$params[$k];
  array_unshift($refs, $types);
  call_user_func_array([$stmt, 'bind_param'], $refs);
}
function select_all(mysqli $con, string $sql, string $types = '', array $params = [])
{
  $st = $con->prepare($sql);
  if (!$st) die('Prepare failed: ' . h($con->error));
  bind_params($st, $types, $params);
  if (!$st->execute()) die('Execute failed: ' . h($st->error));
  $rows = stmt_fetch_all_assoc($st);
  $st->close();
  return $rows;
}
function select_one(mysqli $con, string $sql, string $types = '', array $params = [])
{
  $rows = select_all($con, $sql, $types, $params);
  return $rows ? $rows[0] : null;
}
function action_label($id)
{
  $map = [1 => 'Viewed', 2 => 'Applied', 3 => 'Shared', 4 => 'Saved', 5 => 'Shortlisted', 6 => 'Rejected'];
  $id = (int)$id;
  return $map[$id] ?? ('Action #' . $id);
}
function listing_label($lt)
{
  return ((int)$lt === 1) ? 'Premium' : (((int)$lt === 2) ? 'Standard' : 'Unknown');
}
function report_link($file, array $changes)
{
  $qs = $_GET;
  foreach ($changes as $k => $v) {
    if ($v === null) unset($qs[$k]);
    else $qs[$k] = $v;
  }
  $q = http_build_query($qs);
  return h($file . ($q ? ('?' . $q) : ''));
}

if (!pacific_can_view_this_page($con)) {
  http_response_code(403); ?>
  <!doctype html>
  <html lang="en">

  <head>
    <meta charset="utf-8">
    <title>403 - Forbidden</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/adminconsole/assets/ui.css">
  </head>

  <body>
    <div class="master-wrap">
      <div class="card" style="margin:24px;padding:24px;">
        <h2 style="margin-top:0">Access denied</h2>
        <p>You don't have permission to view this report.</p>
      </div>
    </div>
  </body>

  </html>
<?php exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['admin_id']) || isset($_POST['range']) || isset($_POST['all']))) {
  $range = trim((string)($_POST['range'] ?? ''));
  $from = trim((string)($_POST['from'] ?? ''));
  $to = trim((string)($_POST['to'] ?? ''));
  if ($range === 'daily') {
    $from = date('Y-m-d');
    $to = date('Y-m-d');
  } elseif ($range === 'weekly') {
    $today = (int)date('w');
    $from = date('Y-m-d', strtotime('-' . $today . ' days'));
    $to = date('Y-m-d', strtotime('+' . (6 - $today) . ' days'));
  } elseif ($range === 'monthly') {
    $from = date('Y-m-01');
    $to = date('Y-m-d');
  } elseif ($range === 'lifetime') {
    $from = '';
    $to = '';
  }
  $qs = ['dashboard' => 1, 'admin_id' => (int)($_POST['admin_id'] ?? 0), 'range' => $range, 'all' => 1];
  if ($from !== '') $qs['from'] = $from;
  if ($to !== '') $qs['to'] = $to;
  header('Location: ' . ($_SERVER['PHP_SELF'] ?? 'applications_activity_report.php') . '?' . http_build_query($qs));
  exit;
}

$mode = get_str('mode', '');
if ($mode === 'application') {
  $id = get_int('id', 0);
  if ($id <= 0) die('Invalid application id');
  $row = select_one($con, "
    SELECT A.id AS application_id, A.userid, A.job_id, A.job_listing_type, A.application_date,
           S.name AS status_name, CP.candidate_name, CP.mobile_no, CP.email,
           COALESCE(JP1.name, JP2.name, '') AS job_position,
           COALESCE(JW.company_name, JV.company_name, RP1.organization_name, RP2.organization_name, '') AS company_name,
           COALESCE(RP1.organization_name, RP2.organization_name, RP1.contact_person_name, RP2.contact_person_name, '') AS recruiter_name
    FROM jos_app_applications A
    LEFT JOIN jos_app_applicationstatus S ON S.id=A.status_id
    LEFT JOIN jos_app_candidate_profile CP ON CP.userid=A.userid
    LEFT JOIN jos_app_walkininterviews JW ON (A.job_listing_type=1 AND JW.id=A.job_id)
    LEFT JOIN jos_crm_jobpost JP1 ON JP1.id=JW.job_position_id
    LEFT JOIN jos_app_recruiter_profile RP1 ON RP1.id=JW.recruiter_id
    LEFT JOIN jos_app_jobvacancies JV ON (A.job_listing_type=2 AND JV.id=A.job_id)
    LEFT JOIN jos_crm_jobpost JP2 ON JP2.id=JV.job_position_id
    LEFT JOIN jos_app_recruiter_profile RP2 ON RP2.id=JV.recruiter_id
    WHERE A.id=? LIMIT 1", 'i', [$id]);
  if (!$row) die('Application not found');
  ob_start(); ?>
  <!doctype html>
  <html lang="en">

  <head>
    <meta charset="utf-8">
    <title>Application Details</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/adminconsole/assets/ui.css">
    <style>
      .headbar {
        margin: 0;
        padding: 8px 0 6px;
        position: sticky;
        top: 0;
        z-index: 5;
        background: #0b0f1a
      }

      .grid {
        display: grid;
        grid-template-columns: repeat(2, minmax(240px, 1fr));
        gap: 14px 24px
      }

      .row {
        display: flex;
        gap: 8px
      }

      .lbl {
        min-width: 140px;
        color: #94a3b8
      }

      .val {
        color: #e5e7eb
      }

      .muted {
        color: #9aa0a6
      }
    </style>
  </head>

  <body>
    <div class="master-wrap">
      <div class="headbar" style="display:flex;align-items:center;gap:12px">
        <h2>Application Details</h2>
        <div style="margin-left:auto"><a class="btn secondary" href="<?= base_back_to_list() ?>">Back to List</a></div>
      </div>
      <div class="card" style="padding:20px">
        <div class="grid">
          <?php foreach (
            [
              'Application ID' => $row['application_id'],
              'Applied On' => fmt_date($row['application_date']) . ' ' . fmt_time($row['application_date']),
              'Jobseeker' => $row['candidate_name'] ?: ('User #' . (int)$row['userid']),
              'Mobile' => $row['mobile_no'],
              'Email' => $row['email'],
              'Recruiter' => $row['recruiter_name'],
              'Company' => $row['company_name'],
              'Job Position' => $row['job_position'],
              'Listing Type' => listing_label($row['job_listing_type']),
              'Job ID' => $row['job_id'],
              'Status' => $row['status_name'],
            ] as $label => $val
          ): if (trim((string)$val) === '') continue; ?>
            <div class="row">
              <div class="lbl"><?= h($label) ?></div>
              <div class="val"><?= h($val) ?></div>
            </div>
          <?php endforeach; ?>
        </div>
      </div>
    </div>
  </body>

  </html>
<?php echo ob_get_clean();
  exit;
}

$role_id = pacific_current_role_id($con) ?? $MY_ROLE_ID;
$is_super_admin = ((int)$role_id === 1);
$date_from = normalize_date(get_str('from', ''));
$date_to = normalize_date(get_str('to', ''));
$listing_type = get_int('lt', 0);
$action_type = get_int('action_type', 0);
$candidate_name = get_str('candidate_name', '');
$mobile = get_str('mobile', '');
$application_id = get_int('application_id', 0);
$recruiter = get_str('recruiter', '');
$company = get_str('company', '');
$position = get_str('position', '');
$view_all = get_int('all', 0);
$page = max(1, get_int('page', 1));
$per_page = 50;
$limit = $view_all ? 100000 : $per_page;
$offset = $view_all ? 0 : (($page - 1) * $per_page);

$base_from = "
FROM jos_app_applicationactionlog L
LEFT JOIN jos_app_applications A ON A.id=L.application_id
LEFT JOIN jos_app_candidate_profile CP ON CP.userid=COALESCE(A.userid, L.userid)
LEFT JOIN jos_app_walkininterviews JW ON (L.job_listing_type=1 AND JW.id=L.job_id)
LEFT JOIN jos_crm_jobpost JP1 ON JP1.id=JW.job_position_id
LEFT JOIN jos_app_recruiter_profile RP1 ON RP1.id=JW.recruiter_id
LEFT JOIN jos_app_jobvacancies JV ON (L.job_listing_type=2 AND JV.id=L.job_id)
LEFT JOIN jos_crm_jobpost JP2 ON JP2.id=JV.job_position_id
LEFT JOIN jos_app_recruiter_profile RP2 ON RP2.id=JV.recruiter_id
LEFT JOIN jos_app_users RU ON RU.profile_type_id=1 AND RU.profile_id=COALESCE(JW.recruiter_id, JV.recruiter_id)
WHERE 1=1";

$where = [];
$types = '';
$params = [];
if (!$is_super_admin) {
  $where[] = "AND EXISTS (SELECT 1 FROM jos_app_users U WHERE U.profile_type_id=1 AND U.ac_manager_id=? AND U.profile_id=COALESCE(JW.recruiter_id, JV.recruiter_id))";
  $types .= 'i';
  $params[] = $MY_ID;
}
if ($date_from !== '') {
  $where[] = "AND DATE(L.date)>=?";
  $types .= 's';
  $params[] = $date_from;
}
if ($date_to !== '') {
  $where[] = "AND DATE(L.date)<=?";
  $types .= 's';
  $params[] = $date_to;
}
if ($listing_type === 1 || $listing_type === 2) {
  $where[] = "AND L.job_listing_type=?";
  $types .= 'i';
  $params[] = $listing_type;
}
if ($candidate_name !== '') {
  $where[] = "AND CP.candidate_name LIKE ?";
  $types .= 's';
  $params[] = '%' . $candidate_name . '%';
}
if ($mobile !== '') {
  $where[] = "AND CP.mobile_no LIKE ?";
  $types .= 's';
  $params[] = '%' . $mobile . '%';
}
if ($application_id > 0) {
  $where[] = "AND L.application_id=?";
  $types .= 'i';
  $params[] = $application_id;
}
if ($recruiter !== '') {
  $where[] = "AND COALESCE(RP1.organization_name, RP2.organization_name, RP1.contact_person_name, RP2.contact_person_name, '') LIKE ?";
  $types .= 's';
  $params[] = '%' . $recruiter . '%';
}
if ($company !== '') {
  $where[] = "AND COALESCE(JW.company_name, JV.company_name, RP1.organization_name, RP2.organization_name, '') LIKE ?";
  $types .= 's';
  $params[] = '%' . $company . '%';
}
if ($position !== '') {
  $where[] = "AND COALESCE(JP1.name, JP2.name, '') LIKE ?";
  $types .= 's';
  $params[] = '%' . $position . '%';
}
$where_sql_no_action = "\n" . implode("\n", $where);
$where_sql = $where_sql_no_action;
$list_types = $types;
$list_params = $params;
if ($action_type > 0) {
  $where_sql .= "\nAND L.action_type=?";
  $list_types .= 'i';
  $list_params[] = $action_type;
}

$card_rows = select_all($con, "SELECT L.action_type, COUNT(*) cnt $base_from $where_sql_no_action GROUP BY L.action_type", $types, $params);
$action_counts = [];
$total_activity = 0;
foreach ($card_rows as $r) {
  $action_counts[(int)$r['action_type']] = (int)$r['cnt'];
  $total_activity += (int)$r['cnt'];
}

$total_row = select_one($con, "SELECT COUNT(*) cnt $base_from $where_sql", $list_types, $list_params);
$total_rows = (int)($total_row['cnt'] ?? 0);
$total_pages = $view_all ? 1 : max(1, (int)ceil($total_rows / $per_page));

$rows = select_all($con, "
SELECT L.id AS log_id, L.action_type, L.userid, L.date, L.job_id, L.job_listing_type, L.application_id,
       COALESCE(A.userid, L.userid) AS candidate_userid,
       CP.candidate_name, CP.mobile_no,
       COALESCE(RP1.organization_name, RP2.organization_name, RP1.contact_person_name, RP2.contact_person_name, '') AS recruiter_name,
       COALESCE(JP1.name, JP2.name, '') AS job_position,
       COALESCE(JW.company_name, JV.company_name, RP1.organization_name, RP2.organization_name, '') AS company_name
$base_from
$where_sql
ORDER BY L.date DESC, L.id DESC
LIMIT " . (int)$limit . " OFFSET " . (int)$offset, $list_types, $list_params);

$actions = [1 => 'Viewed', 2 => 'Applied', 3 => 'Shared', 4 => 'Saved', 5 => 'Shortlisted', 6 => 'Rejected'];
ob_start(); ?>
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>Applications Activity</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <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>
    .headbar {
      margin: 0;
      padding: 8px 0 6px;
      position: sticky;
      top: 0;
      z-index: 5;
      /* background: #0b0f1a */
    }

    .muted {
      color: #9aa0a6;
      font-size: 12px
    }

    .nowrap {
      white-space: nowrap
    }

    .cards-row {
      display: flex;
      gap: 12px;
      padding: 6px 2px 10px;
      width: 100%;
      box-sizing: border-box;
      flex-wrap: wrap
    }

     .stat-card {
      flex: 1 1 150px;
      min-width: 120px;
      padding: 14px;
        border: 1px solid #233045;
      border-radius: 14px;
      background: #5C89C1;
      color: #000000;
      text-decoration: none;
    }

     .stat-card:hover {
      border-color: #005d1d;
      background-color: #5C89C1;
      color: white;
    }

    .stat-card.active {
      border-color: #5C89C1;
    }

    .stat-title {
      font-size: 12px;
    }

    .stat-num {
      font-size: 26px;
      font-weight: 700;
      color:white;
    }


    .hide {
      display: none !important
    }

    .toolbar .row {
      display: flex;
      flex-wrap: wrap;
      gap: 12px;
      align-items: end
    }

    .toolbar .group {
      display: flex;
      flex-direction: column;
      min-width: 150px
    }

    .pill {
      padding: 2px 8px;
      border-radius: 999px;
      font-size: 12px;
      border: 1px solid #555
    }

    .pill-premium {
      border-color: #d4af37
    }

    .pill-standard {
      border-color: #666
    }

    .master-wrap .card {
      overflow: hidden
    }

    .table-wrap {
      width: 100%;
      overflow-x: auto
    }

    .table {
      width: 100%
    }

    .table td {
      word-break: break-word
    }

    .table th {
      white-space: nowrap
    }

    .pager {
      display: flex;
      gap: 8px;
      align-items: center;
      justify-content: flex-end;
      padding: 12px;
      flex-wrap: wrap
    }
  </style>
</head>

<body>
  <div class="master-wrap">
    <div class="headbar">
      <div style="display:flex;align-items:center;gap:12px">
        <div>
          <h2 style="margin:0">Applications Activity</h2>
          <div class="muted"><?= $view_all ? 'All' : '50'; ?> records per page - activity logs by application actions.</div>
        </div>
        <div style="margin-left:auto"><a class="btn secondary" href="<?= h(keep_params(['from' => null, 'to' => null, 'lt' => null, 'action_type' => null, 'candidate_name' => null, 'mobile' => null, 'application_id' => null, 'recruiter' => null, 'company' => null, 'position' => null, 'all' => null, 'page' => null, 'dashboard' => null, 'admin_id' => null, 'range' => null])) ?>">Reset</a></div>
      </div>
    </div>
    <div class="cards-row">
      <a class="stat-card <?= $action_type === 0 ? 'active' : '' ?>" href="<?= h(keep_params(['action_type' => null, 'page' => 1])) ?>">
        <div class="stat-title">All Activity</div>
        <div class="stat-num"><?= $total_activity ?></div>
      </a>
      <?php foreach ($actions as $aid => $label): ?><a class="stat-card <?= $action_type === $aid ? 'active' : '' ?>" href="<?= h(keep_params(['action_type' => $aid, 'page' => 1])) ?>">
          <div class="stat-title"><?= h($label) ?></div>
          <div class="stat-num"><?= (int)($action_counts[$aid] ?? 0) ?></div>
        </a><?php endforeach; ?>
      <div style="margin-left:auto;display:flex;align-items:center"><button type="button" id="toggleFilterBtn" class="btn secondary" onclick="toggleFilterBox();return false;">Show Filters</button></div>
    </div>
    <div id="filterPanel" class="card toolbar hide">
      <form method="get">
        <div class="row">
          <div class="group"><label>From Date</label><input placeholder="DD-MM-YYYY" class="inp datepicker" type="text" name="from" value="<?= h($date_from) ?>"></div>
          <div class="group"><label>To Date</label><input placeholder="DD-MM-YYYY" class="inp datepicker" type="text" name="to" value="<?= h($date_to) ?>"></div>
          <div class="group"><label>Recruiter</label><input class="inp" placeholder="Employer Name" type="text" name="recruiter" value="<?= h($recruiter) ?>"></div>
          <div class="group"><label>Company</label><input class="inp" placeholder="Company Name" type="text" name="company" value="<?= h($company) ?>"></div>
          <div class="group"><label>Job Position</label><input class="inp" placeholder="Job Position" type="text" name="position" value="<?= h($position) ?>"></div>
          <div class="group"><label>Listing Type</label><select class="inp" name="lt">
              <option value="0">All</option>
              <option value="1" <?= $listing_type === 1 ? 'selected' : '' ?>>Premium</option>
              <option value="2" <?= $listing_type === 2 ? 'selected' : '' ?>>Standard</option>
            </select></div>
          <div class="group"><label>Action Type</label><select class="inp" name="action_type">
              <option value="0">All</option><?php foreach ($actions as $aid => $label): ?><option value="<?= $aid ?>" <?= $action_type === $aid ? 'selected' : '' ?>><?= h($label) ?></option><?php endforeach; ?>
            </select></div>
          <div class="group"><label>Candidate Name</label><input class="inp" placeholder="Candidate Name" type="text" name="candidate_name" value="<?= h($candidate_name) ?>"></div>
          <div class="group"><label>Mobile Number</label><input class="inp" placeholder="Mobile Number" type="text" name="mobile" value="<?= h($mobile) ?>"></div>
          <div class="group"><label>Application ID</label><input class="inp" placeholder="Application ID" type="number" name="application_id" value="<?= $application_id ?: '' ?>"></div>
          <div class="group"><label>Rows</label><select class="inp" name="all">
              <option value="0" <?= $view_all ? '' : 'selected' ?>>50 rows</option>
              <option value="1" <?= $view_all ? 'selected' : '' ?>>View All</option>
            </select></div>
          <div class="group"><label>&nbsp;</label><button class="btn primary" type="submit">Apply</button></div>
        </div>
      </form>
    </div>
    <div class="card" style="padding:0">
      <div class="table-wrap">
        <table class="table">
          <thead>
            <tr>
              <th>Sr</th>
              <th>Date</th>
              <th>Jobseeker</th>
              <th>Mobile</th>
              <th>Recruiter</th>
              <th>Job Position</th>
              <th>Company</th>
              <th>Listing Type</th>
              <!-- <th>Application ID</th> -->
              <th>Action Type</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php if (!$rows): ?><tr>
                <td colspan="13" style="text-align:center;padding:18px">No records found</td>
              </tr><?php else: $sr = $offset + 1;
                    foreach ($rows as $r):
                      $lt = (int)$r['job_listing_type'];
                      $pill = $lt === 1 ? 'pill-premium' : 'pill-standard'; ?>
                <tr>
                  <td><?= $sr++ ?></td>
                  <td>
                    <div class="nowrap"><?= h(fmt_date($r['date'])) ?></div>
                    <div class="muted"><?= h(fmt_time($r['date'])) ?></div>
                  </td>
                  <td><?= h($r['candidate_name'] ?: ('User #' . (int)$r['candidate_userid'])) ?></td>
                  <td><?= h($r['mobile_no']) ?></td>
                  <td><?= h($r['recruiter_name'] ?: '-') ?></td>
                  <td><?= h($r['job_position'] ?: '-') ?></td>
                  <td><?= h($r['company_name'] ?: '-') ?></td>
                  <td><span class="pill <?= $pill ?>"><?= h(listing_label($lt)) ?></span></td>
                  <!-- <td><?= (int)$r['application_id'] ?></td> -->
                  <td><span class="badge"><?= h(action_label($r['action_type'])) ?></span></td>
                  <td>
                    <div style="display:flex;gap:6px;flex-wrap:wrap"><a class="btn secondary" href="<?= report_link('applications_report.php', ['mode' => 'job', 'lt' => $lt, 'id' => (int)$r['job_id']]) ?>" target="_blank" rel="noopener">View Job</a><a class="btn secondary" href="<?= report_link('applications_report.php', ['mode' => 'candidate', 'userid' => (int)$r['candidate_userid']]) ?>" target="_blank" rel="noopener">View Jobseeker</a><a class="btn secondary" href="<?= h(keep_params(['mode' => 'application', 'id' => (int)$r['application_id']])) ?>" target="_blank" rel="noopener">View Application</a></div>
                  </td>
                </tr>
            <?php endforeach;
                  endif; ?>
          </tbody>
        </table>
      </div>
      <div class="pager"><span class="muted">Total: <?= $total_rows ?></span><?php if (!$view_all && $total_pages > 1): ?><a class="btn secondary" href="<?= h(keep_params(['page' => max(1, $page - 1)])) ?>">Prev</a><span class="muted">Page <?= $page ?> of <?= $total_pages ?></span><a class="btn secondary" href="<?= h(keep_params(['page' => min($total_pages, $page + 1)])) ?>">Next</a><?php endif; ?></div>
    </div>
    <script>
      function toggleFilterBox() {
        var b = document.getElementById('filterPanel'),
          t = document.getElementById('toggleFilterBtn');
        if (!b || !t) return;
        if (b.classList.contains('hide')) {
          b.classList.remove('hide');
          t.innerText = 'Hide Filters'
        } else {
          b.classList.add('hide');
          t.innerText = 'Show Filters'
        }
      }
      document.addEventListener('DOMContentLoaded', function() {
        flatpickr('.datepicker', {
          altInput: true,
          altFormat: 'd-m-Y',
          dateFormat: 'Y-m-d',
          allowInput: false
        });
      });
    </script>
  </div>
</body>

</html>
<?php echo ob_get_clean();
