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

global $con;
if (!isset($con) || !$con) {
    http_response_code(500);
    echo 'DB connection not initialized.';
    exit;
}

date_default_timezone_set('Asia/Kolkata');

$session = $_SESSION['admin_user'];
$role_id = $session['role_id'] ?? 0;

$reportConfig = $reportConfig ?? [];
$targetRoleId = (int)($reportConfig['role_id'] ?? 0);
$profileTypeId = (int)($reportConfig['profile_type_id'] ?? 0);
$pageTitle = (string)($reportConfig['title'] ?? 'Performance Report');
$reportKind = (string)($reportConfig['kind'] ?? 'rm');

if ($targetRoleId <= 0 || !in_array($profileTypeId, [1, 2], true)) {
    http_response_code(500);
    echo 'Invalid report configuration.';
    exit;
}

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

function pr_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 pr_parse_date($value, ?string $fallback): ?string
{
    $value = trim((string)$value);
    if ($value === '') return $fallback;
    foreach (['Y-m-d', 'd-m-Y', 'd/m/Y'] 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) : $fallback;
}

function pr_current_role_id(mysqli $con): int
{
    $me = $_SESSION['admin_user'] ?? [];
    $roleId = (int)($me['role_id'] ?? 0);
    $uid = (int)($me['id'] ?? 0);
    if ($roleId <= 0 && $uid > 0 && pr_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();
        }
    }
    return $roleId;
}

/* MODIFIED: Resolve frontend Employer/Jobseeker login scope without changing superadmin/admin report logic. */
function pr_login_report_scope(mysqli $con): array
{
    $me = $_SESSION['admin_user'] ?? [];
    $adminUserId = (int)($me['id'] ?? 0);
    $roleId = pr_current_role_id($con);
    $appUserId = (int)($me['app_user_id'] ?? 0);
    $profileTypeId = (int)($me['profile_type_id'] ?? 0);
    $roleText = strtolower(trim((string)($me['role_name'] ?? $me['role'] ?? '')));

    if ($adminUserId > 0 && ($appUserId <= 0 || $profileTypeId <= 0) && pr_table_exists($con, 'jos_admin_users')) {
        $st = $con->prepare("SELECT app_user_id FROM jos_admin_users WHERE id=? LIMIT 1");
        if ($st) {
            $st->bind_param('i', $adminUserId);
            $st->execute();
            $appUserId = (int)($st->get_result()->fetch_column() ?: $appUserId);
            $st->close();
        }
    }

    if ($profileTypeId <= 0 && $appUserId > 0 && pr_table_exists($con, 'jos_app_users')) {
        $st = $con->prepare("SELECT profile_type_id FROM jos_app_users WHERE id=? LIMIT 1");
        if ($st) {
            $st->bind_param('i', $appUserId);
            $st->execute();
            $profileTypeId = (int)($st->get_result()->fetch_column() ?: 0);
            $st->close();
        }
    }

    if ($profileTypeId <= 0) {
        if (in_array($roleText, ['employer', 'recruiter'], true)) $profileTypeId = 1;
        if (in_array($roleText, ['jobseeker', 'job seeker', 'candidate'], true)) $profileTypeId = 2;
    }

    return [
        'is_superadmin' => ($roleId === 1),
        'is_front_user' => ($roleId !== 1 && in_array($profileTypeId, [1, 2], true)),
        'admin_user_id' => $adminUserId,
        'profile_type_id' => $profileTypeId,
    ];
}

function pr_acl_allowed(mysqli $con): bool
{
    $roleId = pr_current_role_id($con);
    if ($roleId === 1) return true;
    if (!pr_table_exists($con, 'jos_admin_menus') || !pr_table_exists($con, 'jos_admin_rolemenus')) return false;

    $script = str_replace('\\', '/', $_SERVER['SCRIPT_NAME'] ?? '');
    $base = basename($script);
    $paths = array_values(array_unique([$script, $base, '/adminconsole/operations/' . $base]));
    foreach ($paths as $path) {
        $like = '%' . $path;
        $st = $con->prepare("SELECT rm.can_view
      FROM jos_admin_menus m
      JOIN jos_admin_rolemenus rm ON rm.menu_id=m.id AND rm.role_id=?
      WHERE m.status=1 AND (m.menu_link=? OR m.menu_link LIKE ?)
      LIMIT 1");
        if (!$st) continue;
        $st->bind_param('iss', $roleId, $path, $like);
        $st->execute();
        $can = $st->get_result()->fetch_column();
        $st->close();
        if ((int)$can === 1) return true;
    }
    return false;
}

function pr_add_date_condition(
    string $column,
    ?string $from,
    ?string $to,
    array &$params,
    string &$types
): string {

    // lifetime mode
    if (empty($from) || empty($to)) {
        return '';
    }

    $params[] = $from . ' 00:00:00';
    $params[] = $to . ' 23:59:59';
    $types .= 'ss';

    return " AND {$column} BETWEEN ? AND ?";
}

function pr_employee_where(int $roleId, array $filters, array &$params, string &$types): string
{
    $where = ["(au.role_id=? OR EXISTS (SELECT 1 FROM jos_admin_users_roles ur WHERE ur.user_id=au.id AND ur.role_id=?))"];
    $params[] = $roleId;
    $params[] = $roleId;
    $types .= 'ii';

    if ($filters['name'] !== '') {
        $where[] = "au.name LIKE CONCAT('%',?,'%')";
        $params[] = $filters['name'];
        $types .= 's';
    }
    if ($filters['mobile'] !== '') {
        $where[] = "au.mobile_no LIKE CONCAT('%',?,'%')";
        $params[] = $filters['mobile'];
        $types .= 's';
    }
    if ($filters['location'] !== '') {
        $where[] = "appu.city_id LIKE CONCAT('%',?,'%')";
        $params[] = $filters['location'];
        $types .= 's';
    }
    if ($filters['status'] !== '') {
        $where[] = "au.status=?";
        $params[] = (int)$filters['status'];
        $types .= 'i';
    }
    // if ($filters['user_id'] > 0) {
    //     $where[] = "au.id=?";
    //     $params[] = (int)$filters['user_id'];
    //     $types .= 'i';
    // }
    if ($filters['user_id'] > 0) {

        /* employer/jobseeker login should only see own row */
        $where[] = "(au.id = ? OR au.app_user_id = ?)";

        $params[] = (int)$filters['user_id'];
        $params[] = (int)$filters['user_id'];

        $types .= 'ii';
    }

    return ' WHERE ' . implode(' AND ', $where);
}

function pr_build_report_query(array $cfg, array $filters, bool $withLimit, int $limit = 25, int $offset = 0): array
{
    $params = [];
    $types = '';
    $profileType = (int)$cfg['profile_type_id'];
    $reportKind = (string)($cfg['kind'] ?? 'rm');
    $from = $filters['from'];
    $to = $filters['to'];

    $assignedDate = '';
    $leadsAssignedDate = '';
    $leadsSelfDate = '';
    $revenueDate = '';
    $appsDate2 = '';

    if (!empty($from) && !empty($to)) {

        $assignedDate =
            " AND u.ac_manager_assigned_at BETWEEN '{$from} 00:00:00'
          AND '{$to} 23:59:59' ";

        $leadsAssignedDate =
            " AND l.created_at BETWEEN '{$from} 00:00:00'
          AND '{$to} 23:59:59' ";

        $leadsSelfDate =
            " AND l.created_at BETWEEN '{$from} 00:00:00'
          AND '{$to} 23:59:59' ";

        $revenueDate =
            " AND usl.created_at BETWEEN '{$from} 00:00:00'
          AND '{$to} 23:59:59' ";

        $appsDate2 =
            " AND A.application_date BETWEEN '{$from} 00:00:00'
          AND '{$to} 23:59:59' ";
    }




    $employeeParams = [];
    $employeeTypes = '';
    $where = pr_employee_where((int)$cfg['role_id'], $filters, $employeeParams, $employeeTypes);

    /* ======================================
   OE REPORT JOBSEEKER QUERY ONLY
   ====================================== */

    if ($reportKind === 'oe') {

        $select = "SELECT
    au.id,
    au.name,
    au.mobile_no,
    au.status,
    au.created_at,
    COALESCE(NULLIF(appu.city_id,''), '-') AS location,

    /* Assigned Jobseekers */
    (
        SELECT COUNT(*)
        FROM jos_app_users u
        WHERE u.profile_type_id = 2
        AND u.ac_manager_id = au.id
        AND u.ac_manager_assigned_at IS NOT NULL
        {$assignedDate}
    ) AS assigned_users,

    /* Self Converted Jobseekers */
    0 AS self_converted,

    /* Assigned Leads */
    (
        SELECT COUNT(*)
        FROM jos_app_crm_leads l
        WHERE l.profile_type = 2
        AND l.assigned_to = au.id
        {$leadsAssignedDate}
    ) AS assigned_leads,

    /* Self Leads */
    (
        SELECT COUNT(*)
        FROM jos_app_crm_leads l
        WHERE l.profile_type = 2
        AND l.created_by = au.id
        {$leadsSelfDate}
    ) AS self_leads,

    /* Revenue */
    (
        SELECT COALESCE(SUM(usl.amount_paid),0) * 0.75
        FROM jos_app_users u
        JOIN jos_app_usersubscriptionlog usl
            ON usl.userid = u.id
        WHERE u.profile_type_id = 2
        AND u.ac_manager_id = au.id
        AND u.ac_manager_assigned_at IS NOT NULL
        AND usl.payment_status = 'success'
        AND usl.created_at > u.ac_manager_assigned_at
        {$revenueDate}
    ) AS revenue,

    (
        SELECT COUNT(usl.id)
        FROM jos_app_users u
        JOIN jos_app_usersubscriptionlog usl
            ON usl.userid = u.id
        WHERE u.profile_type_id = 2
        AND u.ac_manager_id = au.id
        AND u.ac_manager_assigned_at IS NOT NULL
        AND usl.payment_status = 'success'
        AND usl.created_at > u.ac_manager_assigned_at
        {$revenueDate}
    ) AS purchases";
        $sql = "{$select}
FROM jos_admin_users au

LEFT JOIN jos_admin_users_roles aur
ON aur.user_id = au.id

LEFT JOIN jos_app_users appu
ON appu.id = au.app_user_id
{$where}

ORDER BY au.name ASC, au.id ASC";
    }

    $joins = "

LEFT JOIN (
    SELECT
        u.ac_manager_id AS employee_id,
        COUNT(*) AS assigned_users
    FROM jos_app_users u
    WHERE u.profile_type_id = 1
    AND u.status_id = 1
    AND u.ac_manager_id IS NOT NULL
    AND u.ac_manager_assigned_at IS NOT NULL
    {$assignedDate}
    GROUP BY u.ac_manager_id
) assigned_users
ON assigned_users.employee_id = au.id

LEFT JOIN (
    SELECT
        assigned_to AS employee_id,
        COUNT(*) AS assigned_leads
    FROM jos_app_crm_leads
    WHERE profile_type = 1
    AND assigned_to IS NOT NULL
    {$leadsAssignedDate}
    GROUP BY assigned_to
) assigned_leads
ON assigned_leads.employee_id = au.id

LEFT JOIN (
    SELECT
        created_by AS employee_id,
        COUNT(*) AS self_leads
    FROM jos_app_crm_leads
    WHERE profile_type = 1
    AND created_by IS NOT NULL
    {$leadsSelfDate}
    GROUP BY created_by
) self_leads
ON self_leads.employee_id = au.id

LEFT JOIN (
    SELECT
        u.ac_manager_id AS employee_id,
        COUNT(usl.id) AS purchases,
        COALESCE(SUM(usl.amount_paid),0) * 0.75 AS revenue
    FROM jos_app_users u
    JOIN jos_app_usersubscriptionlog usl
        ON usl.userid = u.id
    WHERE u.profile_type_id = 1
    AND u.ac_manager_id IS NOT NULL
    AND u.ac_manager_assigned_at IS NOT NULL
    AND usl.payment_status = 'success'
    AND usl.created_at > u.ac_manager_assigned_at
    {$revenueDate}
    GROUP BY u.ac_manager_id
) revenue
ON revenue.employee_id = au.id

LEFT JOIN (
    SELECT
        U.ac_manager_id AS employee_id,
        COUNT(A.id) AS employer_applications,
        SUM(CASE WHEN A.job_listing_type = 1 THEN 1 ELSE 0 END)
            AS premium_applications,
        SUM(CASE WHEN A.job_listing_type = 2 THEN 1 ELSE 0 END)
            AS standard_applications
    FROM jos_app_applications A

    LEFT JOIN jos_app_jobvacancies JV
        ON A.job_listing_type = 2
        AND A.job_id = JV.id

    LEFT JOIN jos_app_walkininterviews WI
        ON A.job_listing_type = 1
        AND A.job_id = WI.id

    LEFT JOIN jos_app_users U
        ON (
            (A.job_listing_type = 2
             AND JV.recruiter_id = U.profile_id)
            OR
            (A.job_listing_type = 1
             AND WI.recruiter_id = U.profile_id)
        )

    WHERE U.ac_manager_id IS NOT NULL
    AND U.profile_type_id = 1
    {$appsDate2}

    GROUP BY U.ac_manager_id
) employer_apps
ON employer_apps.employee_id = au.id
";
    if ($reportKind !== 'oe') {
        $select = "SELECT
au.id,
au.name,
au.mobile_no,
au.status,
au.created_at,
COALESCE(NULLIF(appu.city_id,''), '-') AS location,


/* Assigned Employers */

(
    SELECT COUNT(*)
    FROM jos_app_users u
    WHERE u.profile_type_id = 1
    AND u.status_id = 1
    AND u.ac_manager_id = au.id
    AND u.ac_manager_assigned_at IS NOT NULL
        {$assignedDate}
) AS assigned_users,

/* Self Converted */
0 AS self_converted,

/* Assigned Leads */
(
    SELECT COUNT(*)
    FROM jos_app_crm_leads l
    WHERE l.profile_type = 1
    AND l.assigned_to = au.id
        {$leadsAssignedDate}
) AS assigned_leads,

/* Self Leads */
(
    SELECT COUNT(*)
    FROM jos_app_crm_leads l
    WHERE l.profile_type = 1
    AND l.created_by = au.id
     {$leadsSelfDate}
) AS self_leads,

/* Revenue */
(
    SELECT COALESCE(SUM(usl.amount_paid),0) * 0.75
    FROM jos_app_users u
    JOIN jos_app_usersubscriptionlog usl
        ON usl.userid = u.id
    WHERE u.profile_type_id = 1
    AND u.ac_manager_id = au.id
    AND u.ac_manager_assigned_at IS NOT NULL
    AND usl.payment_status = 'success'
    AND usl.created_at > u.ac_manager_assigned_at
    {$revenueDate}
) AS revenue,

(
    SELECT COUNT(usl.id)
    FROM jos_app_users u
    JOIN jos_app_usersubscriptionlog usl
        ON usl.userid = u.id
    WHERE u.profile_type_id = 1
    AND u.ac_manager_id = au.id
    AND u.ac_manager_assigned_at IS NOT NULL
    AND usl.payment_status = 'success'
    AND usl.created_at > u.ac_manager_assigned_at
) AS purchases,

/* Total Applications */
(
    SELECT COUNT(A.id)
    FROM jos_app_applications A
    LEFT JOIN jos_app_jobvacancies JV
        ON A.job_listing_type = 2
        AND A.job_id = JV.id
    LEFT JOIN jos_app_walkininterviews WI
        ON A.job_listing_type = 1
        AND A.job_id = WI.id
    LEFT JOIN jos_app_users U
        ON (
            (A.job_listing_type = 2 AND JV.recruiter_id = U.profile_id)
            OR
            (A.job_listing_type = 1 AND WI.recruiter_id = U.profile_id)
        )
    WHERE U.ac_manager_id = au.id
    AND U.profile_type_id = 1
    {$appsDate2}
) AS employer_applications,

0 AS interviews,
0 AS placements";
    }
    if ($profileType !== 1) {
        $select .= ", 0 AS employer_applications";
    }
    if ($reportKind !== 'oe') {
        $sql = "{$select}
FROM jos_admin_users au

LEFT JOIN jos_admin_users_roles aur
ON aur.user_id = au.id

LEFT JOIN jos_app_users appu
ON appu.id = au.app_user_id
{$where}

ORDER BY au.name ASC, au.id ASC";
    }
    $params = array_merge($params, $employeeParams);
    $types .= $employeeTypes;
    if ($withLimit) {
        $sql .= " LIMIT ? OFFSET ?";
        $params[] = $limit;
        $params[] = $offset;
        $types .= 'ii';
    }

    return [$sql, $types, $params];
}



function pr_fetch_rows(mysqli $con, array $cfg, array $filters, bool $withLimit, int $limit = 25, int $offset = 0): array
{
    [$sql, $types, $params] = pr_build_report_query($cfg, $filters, $withLimit, $limit, $offset);
    $st = $con->prepare($sql);
    if (!$st) {
        throw new RuntimeException('Report query prepare failed: ' . $con->error);
    }
    if ($types !== '') $st->bind_param($types, ...$params);
    $st->execute();
    $rows = $st->get_result()->fetch_all(MYSQLI_ASSOC);
    $st->close();
    return $rows;
}

function pr_count_rows(mysqli $con, array $cfg, array $filters): int
{
    $params = [];
    $types = '';
    $where = pr_employee_where((int)$cfg['role_id'], $filters, $params, $types);
    $sql = "SELECT COUNT(DISTINCT au.id) AS cnt
    FROM jos_admin_users au
    LEFT JOIN jos_app_users appu ON appu.id=au.id
    {$where}";
    $st = $con->prepare($sql);
    if (!$st) throw new RuntimeException('Count query prepare failed: ' . $con->error);
    $st->bind_param($types, ...$params);
    $st->execute();
    $cnt = (int)($st->get_result()->fetch_assoc()['cnt'] ?? 0);
    $st->close();
    return $cnt;
}

function pr_money($amount): string
{
    return 'Rs. ' . number_format((float)$amount, 2);
}

function pr_metric_cards(array $row, string $kind): array
{
    if ($kind === 'oe') {
        return [
            ['Assigned Jobseekers', (int)$row['assigned_users']],
            ['Self Converted Jobseekers', (int)$row['self_converted']],
            ['Assigned Leads', (int)$row['assigned_leads']],
            ['Self Leads', (int)$row['self_leads']],
            ['Revenue', pr_money($row['revenue'])],
            // ['Today Follow-up', (int)$row['today_followup']],
            // ['Completed', (int)$row['completed_followup']],
            // ['Missed', (int)$row['missed_followup']],
        ];
    }
    return [
        ['Assigned Employers', (int)$row['assigned_users']],
        ['Self Converted Employers', (int)$row['self_converted']],
        ['Assigned Leads', (int)$row['assigned_leads']],
        ['Self Leads', (int)$row['self_leads']],
        ['Revenue', pr_money($row['revenue'])],
        ['Total Applications', (int)$row['employer_applications']],
    ];
}

function pr_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;
}

if (!pr_acl_allowed($con)) {
    http_response_code(403);
    echo '<link rel="stylesheet" href="/adminconsole/assets/ui.css"><div class="master-wrap"><div class="card"><h2>403 - Access denied</h2><div class="alert danger">You do not have permission to view this report.</div></div></div>';
    exit;
}

/* ======================================
   DEFAULT MONTHLY FILTER
   1st date of current month → today
   ====================================== */

$defaultFrom = date('Y-m-01');
$defaultTo = date('Y-m-d');

$filters = [
    'from' => pr_parse_date(
        $_GET['from'] ?? '',
        $defaultFrom
    ),

    'to' => pr_parse_date(
        $_GET['to'] ?? '',
        $defaultTo
    ),

    'name' => trim((string)($_GET['name'] ?? '')),
    'mobile' => trim((string)($_GET['mobile'] ?? '')),
    'location' => trim((string)($_GET['location'] ?? '')),
    'status' => trim((string)($_GET['status'] ?? '')),
    'user_id' => max(0, (int)($_GET['user_id'] ?? 0)),
];

/* MODIFIED: Employer/Jobseeker login can see only own report row; hidden filters are ignored server-side. */
$loginReportScope = pr_login_report_scope($con);
$showAdvancedFilters = true;
if ($loginReportScope['is_front_user']) {
    $filters['name'] = '';
    $filters['mobile'] = '';
    $filters['location'] = '';
    $filters['status'] = '';
    /* show only logged-in employer/jobseeker own record */

    $filters['user_id'] =
        (int)($_SESSION['admin_user']['app_user_id']
            ?? $_SESSION['admin_user']['id']
            ?? 0);
}

/* Performance period text */
$isLifetime = false;
if (
    !empty($filters['from']) &&
    !empty($filters['to']) &&
    $filters['from'] > $filters['to']
) {
    [$filters['from'], $filters['to']] =
        [$filters['to'], $filters['from']];
}

$offset = 0;
try {
    if (isset($_GET['export']) && $_GET['export'] === 'excel') {

        $rows = pr_fetch_rows($con, $reportConfig, $filters, false);

        $filename =
            preg_replace('/[^a-z0-9_]+/i', '_', strtolower($pageTitle))
            . '_' . date('Ymd_His') . '.xls';

        header('Content-Type: application/vnd.ms-excel; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');

        // Dynamic metric headers
        $sampleCards = !empty($rows)
            ? pr_metric_cards($rows[0], $reportKind)
            : [];

        $headers = [
            'Sr No',
            'Employee Name',
            'Mobile Number',
            'Joining Date'
        ];

        foreach ($sampleCards as $card) {
            $headers[] = $card[0]; // card title as column
        }

        echo implode("\t", $headers) . "\n";

        foreach ($rows as $i => $row) {

            $line = [
                ($i + 1),
                str_replace(["\t", "\r", "\n"], ' ', $row['name']),
                str_replace(["\t", "\r", "\n"], ' ', $row['mobile_no']),
                date('d M Y', strtotime($row['created_at']))
            ];

            // Add metric values
            foreach (pr_metric_cards($row, $reportKind) as $card) {
                $line[] = strip_tags((string)$card[1]);
            }

            echo implode("\t", $line) . "\n";
        }

        exit;
    }

    $totalRows = pr_count_rows($con, $reportConfig, $filters);
    $rows = pr_fetch_rows($con, $reportConfig, $filters, false);
} catch (Throwable $e) {
    http_response_code(500);
    echo '<link rel="stylesheet" href="/adminconsole/assets/ui.css"><div class="master-wrap"><div class="card"><h2>Report error</h2><div class="alert danger">' . pr_h($e->getMessage()) . '</div></div></div>';
    exit;
}

?>
<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= pr_h($pageTitle) ?></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>
        body {
            background: #ffffff;
            /* color: #e5e7eb */
        }

        .report-head {
            display: flex;
            justify-content: space-between;
            gap: 14px;
            align-items: flex-start;
            flex-wrap: wrap;
            margin-bottom: 14px
        }

        .report-title {
            font-size: 22px;
            font-weight: 900;
            /* color: #fff; */
            margin: 0
        }

        .report-sub {
            /* color: #94a3b8; */
            margin-top: 4px
        }

        .filters {
            display: grid;
            grid-template-columns: repeat(4, minmax(150px, 1fr));
            gap: 10px;
            margin: 12px 0 16px
        }

        .filters label {
            display: block;
            font-size: 12px;
            /* color: #94a3b8; */
            margin-bottom: 5px
        }

        .filters .inp {
            width: 100%;
            box-sizing: border-box
        }

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

        /* .summary-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(132px, 1fr));
      gap: 8px;
      min-width: 460px
    } */
        .summary-grid {
            display: flex;
            flex-wrap: nowrap;
            /* keep in one row */
            gap: 8px;
            /* overflow-x: auto; */
            /* scroll if cards exceed width */
            min-width: 0;
        }

        .perf-card {
            min-width: 140px;
            /* fixed card width */
            flex: 0 0 auto;
        }

        /* .perf-card {
            background: rgba(255, 255, 255, .045);
            border: 1px solid rgba(255, 255, 255, .09);
            border-radius: 8px;
            padding: 10px;
            transition: .18s
        } */
        .perf-card {
            background: #5C89C1;
            border: 1px solid rgba(255, 255, 255, .09);
            border-radius: 8px;
            padding: 10px;
            transition: .18s;
            color: black;
        }

        .perf-card:hover {
            transform: translateY(-2px);
            border-color: #000000;
            background: #0f3460;
            color: white;
        }

        .perf-label {
            font-size: 11px;
            /* color: #a7b3c7; */
            line-height: 1.25;
            min-height: 28px
        }

        .perf-value {
            font-size: 17px;
            font-weight: 900;
            /* color: #fff; */
            margin-top: 5px;
            word-break: break-word
        }

        .employee-main {
            font-weight: 800;
            /* color: #fff */
        }

        .employee-sub {
            font-size: 12px;
            margin-top: 3px
        }

        .empty-state {
            padding: 34px 12px;
            text-align: center;
            /* color: #94a3b8 */
        }

        .pagination {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
            margin-top: 14px;
            /* color: #94a3b8 */
        }

        thead th {
            position: sticky;
            top: 0;
            z-index: 2;
            background: #5C89C1 !important;
            color: whitesmoke;
            color: var(--text-dark) !important;
            font-weight: 800;
        }

        @media(max-width:1000px) {
            .filters {
                grid-template-columns: repeat(2, minmax(150px, 1fr))
            }

            .summary-grid {
                min-width: 360px
            }
        }

        @media(max-width:700px) {
            .filters {
                grid-template-columns: 1fr
            }

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



            th,
            td {
                white-space: nowrap
            }

            .table-wrap {
                overflow: auto
            }
        }
    </style>
</head>

<body>
    <div class="master-wrap">
        <div class="card">
            <div class="report-head">
                <div>
                    <h1 class="report-title"><?= pr_h($pageTitle) ?></h1>
                    <div class="report-sub">
                        <?php if ($isLifetime): ?>
                            Performance period: Lifetime
                        <?php else: ?>
                            Performance period:
                            <?= pr_h(date('d M Y', strtotime($filters['from']))) ?>
                            to
                            <?= pr_h(date('d M Y', strtotime($filters['to']))) ?>
                        <?php endif; ?>
                    </div>
                </div>
                <?php if ($role_id === 1): ?>
                <div style="display:flex; gap:10px; flex-wrap:wrap;">
                    <a class="btn success"
                        href="<?= pr_h(pr_keep_params([
                                    'export' => 'excel',
                                    'page' => null
                                ])) ?>">
                        Export Excel
                    </a>

                    <button class="btn primary"
                        onclick="printReport()"
                        type="button">
                        Print PDF
                    </button>
                </div>
                <?php endif; ?>
                <!-- <a class="btn success" href="<?= pr_h(pr_keep_params(['export' => 'excel', 'page' => null])) ?>">Export Excel</a> -->
            </div>

            <form method="get">
                <div class="filters">

                    <div><label>From Date</label><input class="inp datepicker" type="text" name="from" value="<?= pr_h($filters['from']) ?>" placeholder="DD-MM-YYYY"></div>
                    <div><label>To Date</label><input class="inp datepicker" type="text" name="to" value="<?= pr_h($filters['to']) ?>" placeholder="DD-MM-YYYY"></div>
                    <?php if ($showAdvancedFilters): // MODIFIED: Employer/Jobseeker login sees date filters only. 
                    ?>
                    <?php if ($role_id === 1): ?>
                        <div><label>Name</label><input class="inp" type="text" name="name" value="<?= pr_h($filters['name']) ?>" placeholder="Name"></div>
                        <div><label>Mobile Number</label><input class="inp" type="text" name="mobile" value="<?= pr_h($filters['mobile']) ?>" placeholder="Mobile number"></div>
                        <div><label>Location</label><input class="inp" type="text" name="location" value="<?= pr_h($filters['location']) ?>" placeholder="City / location"></div>
                        <div>
                            <label>Status</label>
                            <select class="inp" name="status">
                                <option value="" <?= $filters['status'] === '' ? 'selected' : '' ?>>Any</option>
                                <option value="1" <?= $filters['status'] === '1' ? 'selected' : '' ?>>Active</option>
                                <option value="0" <?= $filters['status'] === '0' ? 'selected' : '' ?>>Inactive</option>
                            </select>
                        </div>
                    <?php endif; ?>
                    <?php endif; ?>
                </div>
                <div class="filter-actions">
                    <button class="btn primary" type="submit">Search</button>
                    <a class="btn secondary" href="<?= pr_h(strtok($_SERVER['REQUEST_URI'] ?? '', '?') ?: $_SERVER['PHP_SELF']) ?>">Reset</a>
                </div>
            </form>
        </div>
        <?php if ($loginReportScope['is_superadmin']) : ?>

            <div class="card" style="margin-top:14px">
                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>Sr No</th>
                                <th>Employee Details</th>
                                <!-- <th>Performance Summary</th> -->
                                <th>Counts</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($rows): ?>
                                <?php foreach ($rows as $idx => $row): ?>
                                    <tr>
                                        <td><?= $offset + $idx + 1 ?></td>
                                        <td>
                                            <div class="employee-main">
                                                <?= pr_h($row['name']) ?>
                                            </div>

                                            <div class="employee-sub">
                                                Mobile: <?= pr_h($row['mobile_no'] ?: '-') ?>
                                            </div>

                                            <div class="employee-sub">
                                                Joining:
                                                <?= $row['created_at']
                                                    ? date('d M Y', strtotime((string)$row['created_at']))
                                                    : '-' ?>
                                            </div>

                                            <div class="employee-sub">
                                                <!-- ID: <?= (int)$row['id'] ?> · -->
                                                <?= ((int)$row['status'] === 1)
                                                    ? 'Active'
                                                    : 'Inactive' ?>
                                            </div>
                                        </td>

                                        <!-- <td><?= pr_h($row['location'] ?: '-') ?></td> -->
                                        <td>
                                            <div class="summary-grid">
                                                <?php foreach (pr_metric_cards($row, $reportKind) as $card): ?>
                                                    <div class="perf-card">
                                                        <div class="perf-label"><?= pr_h($card[0]) ?></div>
                                                        <div class="perf-value"><?= pr_h($card[1]) ?></div>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6">
                                        <div class="empty-state">No employees found for the selected filters.</div>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>


            </div>
        <?php else: ?>

            <!-- Employer / Jobseeker Dashboard View -->
            <div class="card" style="margin-top:14px">
<?php
$loggedUserRow = null;
$loggedInId = (int)($_SESSION['admin_user']['app_user_id']
    ?? $_SESSION['admin_user']['id']
    ?? 0);

foreach ($rows as $r) {

    if (
        (int)$r['id'] === $loggedInId
        || (
            !empty($r['app_user_id']) &&
            (int)$r['app_user_id'] === $loggedInId
        )
    ) {
        $loggedUserRow = $r;
        break;
    }
}

/* fallback */
if (!$loggedUserRow && !empty($rows[0])) {
    $loggedUserRow = $rows[0];
}
?>

<?php if (!empty($loggedUserRow)): ?>
    <?php $row = $loggedUserRow; ?>

                    <div style="margin-bottom:20px;">
                        <h3 style="margin:0;">
                            <?= pr_h($row['name']) ?>
                        </h3>

                        <div class="employee-sub">
                            Mobile:
                            <?= pr_h($row['mobile_no'] ?: '-') ?>
                        </div>

                        <div class="employee-sub">
                            Joining:
                            <?= $row['created_at']
                                ? date('d M Y', strtotime($row['created_at']))
                                : '-' ?>
                        </div>
                    </div>

                    <div class="summary-grid">
                        <?php foreach (pr_metric_cards($row, $reportKind) as $card): ?>
                            <div class="perf-card">
                                <div class="perf-label">
                                    <?= pr_h($card[0]) ?>
                                </div>

                                <div class="perf-value">
                                    <?= pr_h($card[1]) ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>

                <?php endif; ?>

            </div>

        <?php endif; ?>
    </div>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            flatpickr(".datepicker", {
                altInput: true,
                altFormat: "d-m-Y",
                dateFormat: "Y-m-d",
                allowInput: false
            });
        });

        function printReport() {

            const rows = <?= json_encode($rows) ?>;
            const reportKind = "<?= $reportKind ?>";
            const pageTitle = "<?= pr_h($pageTitle) ?>";

            let metricHeaders = [];

            if (reportKind === 'oe') {
                metricHeaders = [
                    'Assigned Jobseekers',
                    'Self Converted Jobseekers',
                    'Assigned Leads',
                    'Self Leads',
                    'Revenue'
                ];
            } else {
                metricHeaders = [
                    'Assigned Employers',
                    'Self Converted Employers',
                    'Assigned Leads',
                    'Self Leads',
                    'Revenue',
                    'Total Applications'
                ];
            }

            let tableRows = '';

            rows.forEach((row, index) => {

                let metrics = '';

                if (reportKind === 'oe') {
                    metrics = `
                <td>${row.assigned_users ?? 0}</td>
                <td>${row.self_converted ?? 0}</td>
                <td>${row.assigned_leads ?? 0}</td>
                <td>${row.self_leads ?? 0}</td>
                <td>Rs. ${parseFloat(row.revenue ?? 0).toFixed(2)}</td>
            `;
                } else {
                    metrics = `
                <td>${row.assigned_users ?? 0}</td>
                <td>${row.self_converted ?? 0}</td>
                <td>${row.assigned_leads ?? 0}</td>
                <td>${row.self_leads ?? 0}</td>
                <td>Rs. ${parseFloat(row.revenue ?? 0).toFixed(2)}</td>
                <td>${row.employer_applications ?? 0}</td>
            `;
                }

                tableRows += `
            <tr>
                <td>${index + 1}</td>
                <td>${row.name ?? '-'}</td>
                <td>${row.mobile_no ?? '-'}</td>
                <td>${row.created_at ?? '-'}</td>
                ${metrics}
            </tr>
        `;
            });

            let headerColumns = `
        <th>Sr No</th>
        <th>Employee Name</th>
        <th>Mobile Number</th>
        <th>Joining Date</th>
    `;

            metricHeaders.forEach(header => {
                headerColumns += `<th>${header}</th>`;
            });

            const win = window.open('', '', 'width=1400,height=900');

            win.document.write(`
        <html>
        <head>
            <title>${pageTitle}</title>

            <style>
                body{
                    font-family: Arial, sans-serif;
                    padding:20px;
                }

                h2{
                    margin-bottom:20px;
                }

                table{
                    width:100%;
                    border-collapse: collapse;
                    font-size:12px;
                }

                th, td{
                    border:1px solid #000;
                    padding:8px;
                    text-align:left;
                }

                th{
                    background:#eee;
                }

                @media print{
                    body{
                        margin:0;
                    }

                    table{
                        page-break-inside:auto;
                    }

                    tr{
                        page-break-inside:avoid;
                    }
                }
            </style>
        </head>

        <body>
            <h2>${pageTitle}</h2>

            <table>
                <thead>
                    <tr>
                        ${headerColumns}
                    </tr>
                </thead>

                <tbody>
                    ${tableRows}
                </tbody>
            </table>
        </body>
        </html>
    `);

            win.document.close();

            setTimeout(() => {
                win.print();
                win.close();
            }, 500);
        }
    </script>
</body>

</html>