<?php
@ini_set('display_errors','1'); 
@error_reporting(E_ALL);

require_once __DIR__ . '/../includes/initialize.php';
global $con;
if (!$con) { die('DB connection not initialized'); }

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

/* ----------------------------
   ACL: view-only guard
   - Matches menu using jos_admin_menus.menu_link (normalized path)
   - Allows testing via ?menu_id=#
   - If a matching menu entry is found and the current user's role
     does not have can_view = 1 for that menu, show 403 and exit.
   - If menu is not found, do NOT block (preserve existing behavior).
   ---------------------------- */
try {
  // Helper: get current logged-in user's id
  $current_user_id = null;
  if (function_exists('current_user')) {
    $cu = current_user();
    if (is_array($cu) && isset($cu['id'])) {
      $current_user_id = (int)$cu['id'];
    } elseif (is_object($cu) && isset($cu->id)) {
      $current_user_id = (int)$cu->id;
    }
  }
  // Fallback: some systems store user id in session
  if (!$current_user_id && isset($_SESSION) && isset($_SESSION['user_id'])) {
    $current_user_id = (int)$_SESSION['user_id'];
  }

  // Determine menu id override (testing)
  $menu_id = null;
  if (isset($_GET['menu_id']) && is_numeric($_GET['menu_id'])) {
    $menu_id = (int)$_GET['menu_id'];
  } else {
    // Normalize current request path for matching with jos_admin_menus.menu_link
    $req_uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
    $parsed  = parse_url($req_uri);
    $path    = isset($parsed['path']) ? $parsed['path'] : '/';
    $script  = isset($_SERVER['SCRIPT_NAME']) ? (string)$_SERVER['SCRIPT_NAME'] : $path;

    // Try to find a menu row where menu_link equals path or script, or contains the path.
    $q = "SELECT id, menu_link FROM jos_admin_menus WHERE menu_link = ? OR menu_link = ? OR menu_link LIKE CONCAT('%', ?, '%') LIMIT 1";
    $stmt = $con->prepare($q);
    if ($stmt) {
      $stmt->bind_param('sss', $path, $script, $path);
      $stmt->execute();
      $res = $stmt->get_result();
      $menu_row = $res ? $res->fetch_assoc() : null;
      $stmt->close();
      if ($menu_row && isset($menu_row['id'])) {
        $menu_id = (int)$menu_row['id'];
      }
    }
  }

  // If we resolved a menu_id and we also have a user id, check role permissions.
  if ($menu_id && $current_user_id) {
    // Resolve role_id for the current user (jos_admin_users_roles)
    $role_id = null;
    $q = "SELECT role_id FROM jos_admin_users_roles WHERE user_id = ? LIMIT 1";
    $stmt = $con->prepare($q);
    if ($stmt) {
      $stmt->bind_param('i', $current_user_id);
      $stmt->execute();
      $stmt->bind_result($rid);
      if ($stmt->fetch()) { $role_id = (int)$rid; }
      $stmt->close();
    }

    // If we have a resolved role_id, check jos_admin_rolemenus.can_view
    if ($role_id) {
      $can_view = 0;
      $q = "SELECT can_view FROM jos_admin_rolemenus WHERE role_id = ? AND menu_id = ? LIMIT 1";
      $stmt = $con->prepare($q);
      if ($stmt) {
        $stmt->bind_param('ii', $role_id, $menu_id);
        $stmt->execute();
        $stmt->bind_result($cv);
        if ($stmt->fetch()) { $can_view = (int)$cv; }
        $stmt->close();
      }

      if ($can_view !== 1) {
        // Render 403 Access denied (styled with adminconsole/assets/ui.css)
        http_response_code(403);
        ob_start(); ?>
        <link rel="stylesheet" href="/adminconsole/assets/ui.css">
        <div class="master-wrap" style="padding:40px">
          <div class="headbar"><h2 style="margin:0">Access denied</h2></div>
          <div class="card" style="padding:20px;margin-top:12px">
            <div style="font-size:18px;font-weight:700;color:#fff">403 — Access denied</div>
            <div style="color:#9ca3af;margin-top:8px">
              You do not have permission to view this page.
            </div>
            <div style="margin-top:12px">
              <a class="btn secondary" href="javascript:history.back()">← Go back</a>
            </div>
          </div>
        </div>
        <?php
        echo ob_get_clean();
        exit;
      }
    }
    // If no role_id found, behave permissively (do not block).
  }
  // If no menu_id resolved or no current_user_id, do not block (preserve existing behavior).
} catch (Exception $e) {
  // On any unexpected error during ACL check, do not block; preserve existing behavior.
}

/* ---------- Ensure DOMAIN_URL if not defined (used for images/logos) ---------- */
if (!defined('DOMAIN_URL')) {
    define('DOMAIN_URL', '/');
}

/* ---------------- Helpers ---------------- */
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
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 get_int($key,$default=0){ return isset($_GET[$key]) ? (int)$_GET[$key] : $default; }
function get_str($key,$default=''){ return isset($_GET[$key]) ? trim((string)$_GET[$key]) : $default; }
function fmt_date($s){ return $s ? date('d M Y', strtotime($s)) : ''; }

/* ---------- Paths to existing detail reports ---------- */
$PREMIUM_REPORT  = '/adminconsole/operations/premium_jobs_report.php';
$STANDARD_REPORT = '/adminconsole/operations/standard_jobs_report.php';

/* ======================================================================
   JOB POSITION-WISE SUMMARY
   ====================================================================== */

$page_title        = 'Matching Jobs';
$DEFAULT_PAGE_SIZE = 50;

$q        = get_str('q','');              // search by job position name
$sort     = get_str('sort','alpha');      // alpha | total_desc | total_asc
$view     = get_str('view','last50');     // last50 | all
$page     = max(1, get_int('page',1));
$per_page = ($view === 'all') ? 1000 : $DEFAULT_PAGE_SIZE;

/* Build base SQL:
   - jp: job positions (jos_crm_jobpost)
   - p:  premium jobs count from jos_app_walkininterviews
   - s:  standard jobs count from jos_app_jobvacancies
*/
$sql = "
  SELECT 
    jp.id AS job_position_id,
    jp.name AS job_position,
    COALESCE(p.premium_count, 0)  AS premium_jobs,
    COALESCE(s.standard_count, 0) AS standard_jobs,
    COALESCE(p.premium_count, 0) + COALESCE(s.standard_count, 0) AS total_jobs
  FROM jos_crm_jobpost jp
  LEFT JOIN (
      SELECT job_position_id, COUNT(*) AS premium_count
      FROM jos_app_walkininterviews
      -- WHERE job_status_id = 1  -- uncomment if you want only active premium jobs
      GROUP BY job_position_id
  ) p ON p.job_position_id = jp.id
  LEFT JOIN (
      SELECT job_position_id, COUNT(*) AS standard_count
      FROM jos_app_jobvacancies
      -- WHERE job_status_id = 1  -- uncomment if you want only active standard jobs
      GROUP BY job_position_id
  ) s ON s.job_position_id = jp.id
  WHERE (COALESCE(p.premium_count,0) + COALESCE(s.standard_count,0)) > 0
";

$types  = '';
$params = [];

// Search by job position name
if ($q !== '') {
  $sql .= " AND jp.name LIKE CONCAT('%', ?, '%')";
  $types .= 's';
  $params[] = $q;
}

// Sorting
if ($sort === 'total_desc') {
  $sql .= " ORDER BY total_jobs DESC, jp.name ASC";
} elseif ($sort === 'total_asc') {
  $sql .= " ORDER BY total_jobs ASC, jp.name ASC";
} else { // alpha
  $sql .= " ORDER BY jp.name ASC";
}

// Execute & fetch all, then paginate in PHP
$stmt = $con->prepare($sql);
if ($types) {
  $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$res = $stmt->get_result();
$allRows = [];
while($r = $res->fetch_assoc()){ $allRows[] = $r; }
$stmt->close();

$total = count($allRows);
$pages = ($view === 'all') ? 1 : max(1, ceil($total / $per_page));
if ($page > $pages) { $page = $pages; }
$offset = ($view === 'all') ? 0 : (($page - 1) * $per_page);
$rows   = ($view === 'all') ? $allRows : array_slice($allRows, $offset, $per_page);

/* Build return URL for detail reports (used for Back button there) */
$SUMMARY_PATH      = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : '/adminconsole/operations/jobpost_summary.php';
$currentSummaryUrl = $SUMMARY_PATH . keep_params([]); // keeps q, sort, view, page
$returnParam       = urlencode($currentSummaryUrl);

/* Render summary */
ob_start(); ?>
<link rel="stylesheet" href="/adminconsole/assets/ui.css">
<div class="master-wrap">
  <div class="headbar">
    <h2 style="margin:0"><?= h($page_title) ?></h2>
  </div>

  <div class="card">
    <form method="get" class="toolbar" style="gap:10px;flex-wrap:wrap">
      <input class="inp" type="text" name="q" value="<?= h($q) ?>" placeholder="Search job position..." style="min-width:240px">

      <select class="inp" name="sort">
        <option value="alpha"      <?= $sort==='alpha'?'selected':''; ?>>Sort: A → Z</option>
        <option value="total_desc" <?= $sort==='total_desc'?'selected':''; ?>>Sort: Total Jobs (High → Low)</option>
        <option value="total_asc"  <?= $sort==='total_asc'?'selected':''; ?>>Sort: Total Jobs (Low → High)</option>
      </select>

      <button class="btn primary" type="submit">Apply</button>

      <div style="flex:1"></div>
      <a class="btn secondary" href="<?= h(keep_params(['view'=>'last50','page'=>1])) ?>">Last <?= $DEFAULT_PAGE_SIZE ?></a>
      <a class="btn secondary" href="<?= h(keep_params(['view'=>'all','page'=>1])) ?>">View All</a>
    </form>

    <div style="display:flex;align-items:center;gap:12px;margin:8px 0 12px">
      <span class="badge">Positions: <?= (int)$total ?></span>
      <span class="badge">Showing: <?= ($view==='all') ? 'All' : count($rows) ?></span>
      <?php if($view!=='all'){ ?>
        <div style="margin-left:auto;display:flex;gap:6px;align-items:center">
          <?php if($page>1){ ?><a class="btn secondary" href="<?= h(keep_params(['page'=>$page-1])) ?>">‹ Prev</a><?php } ?>
          <span>Page <?= (int)$page ?> / <?= (int)$pages ?></span>
          <?php if($page<$pages){ ?><a class="btn secondary" href="<?= h(keep_params(['page'=>$page+1])) ?>">Next ›</a><?php } ?>
        </div>
      <?php } ?>
    </div>

    <div class="table-wrap">
      <table class="table">
        <thead>
          <tr>
            <th style="width:70px;">SR No</th>
            <th>Job Position</th>
            <th style="width:120px;">Total Jobs</th>
            <th style="width:150px;">Premium Jobs</th>
            <th style="width:150px;">Standard Jobs</th>
          </tr>
        </thead>
        <tbody>
        <?php
          $srStart = ($view === 'all') ? 1 : ($offset + 1);
          $sr = $srStart;

          if (!$rows) {
            echo '<tr><td colspan="5" style="text-align:center;color:#9ca3af">No job positions found.</td></tr>';
          } else {
            foreach($rows as $r){
              $premium  = (int)$r['premium_jobs'];
              $standard = (int)$r['standard_jobs'];
              $totalJ   = (int)$r['total_jobs'];

              // URLs to external reports, with position_id and return URL
              $premiumUrl  = $PREMIUM_REPORT
                           . '?position_id='.(int)$r['job_position_id']
                           . '&return='.$returnParam;

              $standardUrl = $STANDARD_REPORT
                           . '?position_id='.(int)$r['job_position_id']
                           . '&return='.$returnParam;

              echo '<tr>';
              echo '<td>'.(int)$sr.'</td>';
              echo '<td>'.h($r['job_position'] ?? '').'</td>';
              echo '<td>'.$totalJ.'</td>';

              // Premium cell
              echo '<td>';
              if ($premium > 0) {
                echo '<a class="btn secondary" href="'.$premiumUrl.'" '.
                     'style="padding:2px 8px;font-size:12px;text-decoration:none !important;">'.
                     'Premium ('.$premium.')'.
                     '</a>';
              } else {
                echo '<span class="badge" style="opacity:0.6">0</span>';
              }
              echo '</td>';

              // Standard cell
              echo '<td>';
              if ($standard > 0) {
                echo '<a class="btn secondary" href="'.$standardUrl.'" '.
                     'style="padding:2px 8px;font-size:12px;text-decoration:none !important;">'.
                     'Standard ('.$standard.')'.
                     '</a>';
              } else {
                echo '<span class="badge" style="opacity:0.6">0</span>';
              }
              echo '</td>';

              echo '</tr>';
              $sr++;
            }
          }
        ?>
        </tbody>
      </table>
    </div>

    <?php if($view!=='all' && $rows){ ?>
      <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:12px">
        <?php if($page>1){ ?><a class="btn secondary" href="<?= h(keep_params(['page'=>$page-1])) ?>">‹ Prev</a><?php } ?>
        <span class="badge">Page <?= (int)$page ?> / <?= (int)$pages ?></span>
        <?php if($page<$pages){ ?><a class="btn secondary" href="<?= h(keep_params(['page'=>$page+1])) ?>">Next ›</a><?php } ?>
      </div>
    <?php } ?>
  </div>
</div>
<?php
echo ob_get_clean();
