<?php
declare(strict_types=1);

require_once __DIR__ . '/../app/init.php';
app_require_login();

$requestedCompanyId = (int) ($_GET['company_id'] ?? 0);
$companyId = app_effective_company_id($requestedCompanyId > 0 ? $requestedCompanyId : null, true);
if ($companyId !== null && $companyId > 0) {
    app_set_context_company_id($companyId);
}
$company = $companyId ? app_company_by_id((int) $companyId) : null;
$isArabic = app_ui_language() === 'ar';
$txt = static fn (string $en, string $ar): string => $isArabic ? $ar : $en;
$fromDate = app_sanitize_date((string) ($_GET['from_date'] ?? date('Y-01-01')), date('Y-01-01'));
$toDate = app_sanitize_date((string) ($_GET['to_date'] ?? date('Y-m-d')), date('Y-m-d'));
if ($fromDate > $toDate) {
    [$fromDate, $toDate] = [$toDate, $fromDate];
}
$activeReport = app_normalize_whitespace((string) ($_GET['report'] ?? 'overview'));
if (!in_array($activeReport, ['overview', 'payroll', 'attendance', 'leaves', 'contracts', 'components'], true)) {
    $activeReport = 'overview';
}
$activeReportPrintLabel = [
    'overview' => $txt('HR Reports', 'تقارير الموارد البشرية'),
    'payroll' => $txt('Payroll Report', 'تقرير الرواتب'),
    'attendance' => $txt('Attendance Report', 'تقرير الحضور'),
    'leaves' => $txt('Leaves Report', 'تقرير الإجازات'),
    'contracts' => $txt('Contracts Report', 'تقرير العقود'),
    'components' => $txt('Salary Components Report', 'تقرير بنود الرواتب'),
][$activeReport] ?? $txt('HR Reports', 'تقارير الموارد البشرية');
$companyQuery = $companyId ? ('company_id=' . urlencode((string) $companyId)) : '';
$pdo = app_pdo();

$countStmt = static function (string $sql, array $params = []) use ($pdo): float {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    return app_number($stmt->fetchColumn());
};
$fetchRows = static function (string $sql, array $params = []) use ($pdo): array {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchAll() ?: [];
};

$params = [
    'company_id' => $companyId,
    'from_date' => $fromDate,
    'to_date' => $toDate,
];
$employeeCount = $countStmt('SELECT COUNT(*) FROM employees WHERE company_id = :company_id', ['company_id' => $companyId]);
$activeEmployeeCount = $countStmt('SELECT COUNT(*) FROM employees WHERE company_id = :company_id AND is_active = 1', ['company_id' => $companyId]);
$departmentCount = $countStmt('SELECT COUNT(*) FROM hr_departments WHERE company_id = :company_id', ['company_id' => $companyId]);
$contractCount = $countStmt('SELECT COUNT(*) FROM hr_employee_contracts WHERE company_id = :company_id', ['company_id' => $companyId]);
$payrollItemTotal = $countStmt('SELECT COALESCE(SUM(amount), 0) FROM hr_payroll_items WHERE company_id = :company_id', ['company_id' => $companyId]);
$payrollNet = $countStmt(
    'SELECT COALESCE(SUM(total_net), 0)
     FROM payroll_runs
     WHERE company_id = :company_id
       AND STR_TO_DATE(CONCAT(period_year, "-", LPAD(period_month, 2, "0"), "-01"), "%Y-%m-%d") BETWEEN :from_date AND :to_date',
    $params
);
$attendanceRows = $fetchRows(
    'SELECT status, COUNT(*) AS records, COALESCE(SUM(hours_worked), 0) AS hours_worked
     FROM hr_attendance
     WHERE company_id = :company_id
       AND attendance_date BETWEEN :from_date AND :to_date
     GROUP BY status
     ORDER BY status ASC',
    $params
);
$leaveRows = $fetchRows(
    'SELECT status, COUNT(*) AS records, COALESCE(SUM(days_count), 0) AS days_count
     FROM hr_leave_requests
     WHERE company_id = :company_id
       AND start_date <= :to_date
       AND end_date >= :from_date
     GROUP BY status
     ORDER BY status ASC',
    $params
);
$payrollRows = $fetchRows(
    'SELECT run_number, period_month, period_year, total_gross, total_deductions, total_net, status
     FROM payroll_runs
     WHERE company_id = :company_id
       AND STR_TO_DATE(CONCAT(period_year, "-", LPAD(period_month, 2, "0"), "-01"), "%Y-%m-%d") BETWEEN :from_date AND :to_date
     ORDER BY period_year DESC, period_month DESC, id DESC',
    $params
);
$departmentRows = $fetchRows(
    'SELECT d.department_code, d.department_name, COUNT(e.id) AS employees_count, COALESCE(SUM(e.basic_salary + e.allowance - e.deduction_default), 0) AS estimated_net
     FROM hr_departments d
     LEFT JOIN employees e ON e.company_id = d.company_id AND e.department_code = d.department_code
     WHERE d.company_id = :company_id
     GROUP BY d.department_code, d.department_name
     ORDER BY d.department_code ASC',
    ['company_id' => $companyId]
);
$contractRows = $fetchRows(
    'SELECT c.contract_number, c.employee_number, COALESCE(e.full_name, c.employee_number) AS employee_name,
            c.department_code, c.job_code, c.contract_type, c.start_date, c.end_date,
            c.basic_salary, c.allowance, c.status
     FROM hr_employee_contracts c
     LEFT JOIN employees e ON e.company_id = c.company_id AND e.employee_number = c.employee_number
     WHERE c.company_id = :company_id
       AND c.start_date <= :to_date
       AND (c.end_date IS NULL OR c.end_date >= :from_date)
     ORDER BY c.start_date DESC, c.contract_number DESC',
    $params
);
$componentRows = $fetchRows(
    'SELECT component_code, component_name, component_type, calculation_type, default_amount, percent_value, account_code, is_active
     FROM hr_salary_components
     WHERE company_id = :company_id
     ORDER BY component_type ASC, component_code ASC',
    ['company_id' => $companyId]
);
$payrollItemRows = $fetchRows(
    'SELECT i.run_number, i.employee_number, COALESCE(e.full_name, i.employee_number) AS employee_name,
            i.component_code, i.component_type, i.amount, i.account_code, i.cost_center_code
     FROM hr_payroll_items i
     LEFT JOIN employees e ON e.company_id = i.company_id AND e.employee_number = i.employee_number
     WHERE i.company_id = :company_id
     ORDER BY i.run_number DESC, i.employee_number ASC, i.component_code ASC',
    ['company_id' => $companyId]
);

if (app_normalize_whitespace((string) ($_GET['export'] ?? '')) === 'xlsx') {
    app_export_xlsx('hr-report-' . date('Ymd-His') . '.xlsx', [
        'Summary' => [
            app_xlsx_row(['HR Report'], 'title'),
            ['Company', (string) ($company['name'] ?? '')],
            ['From', $fromDate],
            ['To', $toDate],
            [],
            ['Metric', 'Value'],
            ['Employees', $employeeCount],
            ['Active Employees', $activeEmployeeCount],
            ['Departments', $departmentCount],
            ['Contracts', $contractCount],
            ['Payroll Net', $payrollNet],
            ['Payroll Items Total', $payrollItemTotal],
        ],
        'Attendance' => array_merge([['Status', 'Records', 'Hours Worked']], array_map(static fn (array $row): array => [(string) ($row['status'] ?? ''), (int) ($row['records'] ?? 0), app_number($row['hours_worked'] ?? 0)], $attendanceRows)),
        'Leaves' => array_merge([['Status', 'Records', 'Days']], array_map(static fn (array $row): array => [(string) ($row['status'] ?? ''), (int) ($row['records'] ?? 0), app_number($row['days_count'] ?? 0)], $leaveRows)),
        'Payroll' => array_merge([['Run', 'Month', 'Year', 'Gross', 'Deductions', 'Net', 'Status']], array_map(static fn (array $row): array => [(string) ($row['run_number'] ?? ''), (int) ($row['period_month'] ?? 0), (int) ($row['period_year'] ?? 0), app_number($row['total_gross'] ?? 0), app_number($row['total_deductions'] ?? 0), app_number($row['total_net'] ?? 0), (string) ($row['status'] ?? '')], $payrollRows)),
        'Payroll Items' => array_merge([['Run', 'Employee', 'Component', 'Type', 'Amount', 'Account', 'Cost Center']], array_map(static fn (array $row): array => [(string) ($row['run_number'] ?? ''), (string) ($row['employee_name'] ?? ''), (string) ($row['component_code'] ?? ''), (string) ($row['component_type'] ?? ''), app_number($row['amount'] ?? 0), (string) ($row['account_code'] ?? ''), (string) ($row['cost_center_code'] ?? '')], $payrollItemRows)),
        'Contracts' => array_merge([['Contract', 'Employee', 'Department', 'Job', 'Type', 'Start', 'End', 'Salary', 'Allowance', 'Status']], array_map(static fn (array $row): array => [(string) ($row['contract_number'] ?? ''), (string) ($row['employee_name'] ?? ''), (string) ($row['department_code'] ?? ''), (string) ($row['job_code'] ?? ''), (string) ($row['contract_type'] ?? ''), (string) ($row['start_date'] ?? ''), (string) ($row['end_date'] ?? ''), app_number($row['basic_salary'] ?? 0), app_number($row['allowance'] ?? 0), (string) ($row['status'] ?? '')], $contractRows)),
        'Salary Components' => array_merge([['Code', 'Name', 'Type', 'Calculation', 'Default', 'Percent', 'Account', 'Active']], array_map(static fn (array $row): array => [(string) ($row['component_code'] ?? ''), (string) ($row['component_name'] ?? ''), (string) ($row['component_type'] ?? ''), (string) ($row['calculation_type'] ?? ''), app_number($row['default_amount'] ?? 0), app_number($row['percent_value'] ?? 0), (string) ($row['account_code'] ?? ''), (int) ($row['is_active'] ?? 0)], $componentRows)),
    ]);
}
?>
<!doctype html>
<html <?= app_html_attrs() ?>>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= app_escape((string) app_config('app_name')) ?> - <?= app_escape($txt('HR Reports', 'تقارير الموارد البشرية')) ?></title>
  <link rel="icon" href="assets/favicon.svg" type="image/svg+xml">
  <link rel="shortcut icon" href="assets/favicon.svg" type="image/svg+xml">
  <link rel="stylesheet" href="assets/styles.css">
</head>
<body>
<div class="app-shell has-sidebar">
  <?= app_sidebar_nav_html('hr_reports', null, $companyId) ?>
  <div class="workspace-page">
    <section class="workspace-hero workspace-hero--hr">
      <div>
        <a class="workspace-back" href="hr.php<?= $companyId ? '?company_id=' . (int) $companyId : '' ?>"><?= app_escape($txt('Back to HR', 'رجوع للموارد البشرية')) ?></a>
        <h1><?= app_escape($txt('HR Reports', 'تقارير الموارد البشرية')) ?></h1>
        <p><?= app_escape($txt('Employee, attendance, leave, and payroll reports in one HR-only screen.', 'تقارير الموظفين والحضور والإجازات والرواتب في شاشة منفصلة للموارد البشرية.')) ?></p>
      </div>
      <img src="<?= app_escape(app_logo_path_for_header($company)) ?>" alt="Company Logo">
    </section>

    <section class="erp-control-panel screen-only">
      <div class="erp-control-main">
        <div>
          <h1><?= app_escape($txt('Filters', 'الفلاتر')) ?></h1>
          <p><?= app_escape($txt('Choose report type and date range.', 'اختر نوع التقرير ونطاق التاريخ.')) ?></p>
        </div>
        <form method="get" class="erp-search">
          <?php if ($companyId !== null): ?>
            <input type="hidden" name="company_id" value="<?= (int) $companyId ?>">
          <?php endif; ?>
          <select name="report">
            <option value="overview" <?= $activeReport === 'overview' ? 'selected' : '' ?>><?= app_escape($txt('Overview', 'نظرة عامة')) ?></option>
            <option value="payroll" <?= $activeReport === 'payroll' ? 'selected' : '' ?>><?= app_escape($txt('Payroll', 'الرواتب')) ?></option>
            <option value="attendance" <?= $activeReport === 'attendance' ? 'selected' : '' ?>><?= app_escape($txt('Attendance', 'الحضور')) ?></option>
            <option value="leaves" <?= $activeReport === 'leaves' ? 'selected' : '' ?>><?= app_escape($txt('Leaves', 'الإجازات')) ?></option>
            <option value="contracts" <?= $activeReport === 'contracts' ? 'selected' : '' ?>><?= app_escape($txt('Contracts', 'العقود')) ?></option>
            <option value="components" <?= $activeReport === 'components' ? 'selected' : '' ?>><?= app_escape($txt('Salary Components', 'بنود الرواتب')) ?></option>
          </select>
          <input type="date" name="from_date" value="<?= app_escape($fromDate) ?>">
          <input type="date" name="to_date" value="<?= app_escape($toDate) ?>">
          <button class="btn btn-primary" type="submit"><?= app_escape($txt('Search', 'بحث')) ?></button>
          <button class="btn btn-secondary" type="button" data-print-page><?= app_escape($txt('Print', 'طباعة')) ?></button>
          <a class="btn btn-secondary" href="hr_reports.php?<?= app_escape(http_build_query(['company_id' => $companyId, 'report' => $activeReport, 'from_date' => $fromDate, 'to_date' => $toDate, 'export' => 'xlsx'])) ?>">Export XLSX</a>
        </form>
      </div>
    </section>

    <main
      id="hrReportPrintArea"
      class="print-scope"
      data-print-scope
      data-default-print-target
      data-report-print
      data-print-title="<?= app_escape($activeReportPrintLabel) ?>"
      data-print-logo="<?= app_escape(app_logo_path_for_header($company)) ?>"
    >
    <section class="workspace-kpis">
      <div class="workspace-kpi"><span><?= app_escape($txt('Employees', 'الموظفون')) ?></span><strong><?= app_escape(number_format($employeeCount)) ?></strong></div>
      <div class="workspace-kpi"><span><?= app_escape($txt('Active Employees', 'الموظفون النشطون')) ?></span><strong><?= app_escape(number_format($activeEmployeeCount)) ?></strong></div>
      <div class="workspace-kpi"><span><?= app_escape($txt('Contracts', 'العقود')) ?></span><strong><?= app_escape(number_format($contractCount)) ?></strong></div>
      <div class="workspace-kpi"><span><?= app_escape($txt('Payroll Items', 'بنود الرواتب')) ?></span><strong><?= app_escape(app_money_format($payrollItemTotal)) ?></strong></div>
    </section>

    <?php if ($activeReport === 'overview' || $activeReport === 'attendance'): ?>
      <section class="table-card">
        <div class="table-header"><div><h3><?= app_escape($txt('Attendance Summary', 'ملخص الحضور')) ?></h3><div class="hint"><?= app_escape($fromDate) ?> - <?= app_escape($toDate) ?></div></div></div>
        <div class="table-wrap">
          <table class="data-table">
            <thead><tr><th><?= app_escape($txt('Status', 'الحالة')) ?></th><th><?= app_escape($txt('Records', 'السجلات')) ?></th><th><?= app_escape($txt('Hours Worked', 'ساعات العمل')) ?></th></tr></thead>
            <tbody>
              <?php foreach ($attendanceRows as $row): ?>
                <tr><td><?= app_escape((string) ($row['status'] ?? '')) ?></td><td><?= app_escape(number_format((int) ($row['records'] ?? 0))) ?></td><td><?= app_escape(app_money_format($row['hours_worked'] ?? 0)) ?></td></tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </section>
    <?php endif; ?>

    <?php if ($activeReport === 'overview' || $activeReport === 'leaves'): ?>
      <section class="table-card">
        <div class="table-header"><div><h3><?= app_escape($txt('Leave Summary', 'ملخص الإجازات')) ?></h3><div class="hint"><?= app_escape($fromDate) ?> - <?= app_escape($toDate) ?></div></div></div>
        <div class="table-wrap">
          <table class="data-table">
            <thead><tr><th><?= app_escape($txt('Status', 'الحالة')) ?></th><th><?= app_escape($txt('Records', 'السجلات')) ?></th><th><?= app_escape($txt('Days', 'الأيام')) ?></th></tr></thead>
            <tbody>
              <?php foreach ($leaveRows as $row): ?>
                <tr><td><?= app_escape((string) ($row['status'] ?? '')) ?></td><td><?= app_escape(number_format((int) ($row['records'] ?? 0))) ?></td><td><?= app_escape(app_money_format($row['days_count'] ?? 0)) ?></td></tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </section>
    <?php endif; ?>

    <?php if ($activeReport === 'overview' || $activeReport === 'payroll'): ?>
      <section class="table-card">
        <div class="table-header"><div><h3><?= app_escape($txt('Payroll Runs', 'تشغيل الرواتب')) ?></h3><div class="hint"><?= app_escape($fromDate) ?> - <?= app_escape($toDate) ?></div></div></div>
        <div class="table-wrap">
          <table class="data-table">
            <thead><tr><th><?= app_escape($txt('Run', 'التشغيل')) ?></th><th><?= app_escape($txt('Period', 'الفترة')) ?></th><th><?= app_escape($txt('Gross', 'الإجمالي')) ?></th><th><?= app_escape($txt('Deductions', 'الاستقطاعات')) ?></th><th><?= app_escape($txt('Net', 'الصافي')) ?></th><th><?= app_escape($txt('Status', 'الحالة')) ?></th></tr></thead>
            <tbody>
              <?php foreach ($payrollRows as $row): ?>
                <tr>
                  <td><?= app_escape((string) ($row['run_number'] ?? '')) ?></td>
                  <td><?= app_escape(str_pad((string) ($row['period_month'] ?? ''), 2, '0', STR_PAD_LEFT) . '/' . (string) ($row['period_year'] ?? '')) ?></td>
                  <td><?= app_escape(app_money_format($row['total_gross'] ?? 0)) ?></td>
                  <td><?= app_escape(app_money_format($row['total_deductions'] ?? 0)) ?></td>
                  <td><?= app_escape(app_money_format($row['total_net'] ?? 0)) ?></td>
                  <td><?= app_escape((string) ($row['status'] ?? '')) ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </section>
    <?php endif; ?>

    <?php if ($activeReport === 'overview' || $activeReport === 'payroll'): ?>
      <section class="table-card">
        <div class="table-header"><div><h3><?= app_escape($txt('Payroll Items', 'بنود الرواتب')) ?></h3><div class="hint"><?= app_escape($txt('Detailed payroll lines by employee and salary component.', 'بنود الرواتب التفصيلية حسب الموظف والبند.')) ?></div></div></div>
        <div class="table-wrap">
          <table class="data-table" style="min-width: 980px;">
            <thead><tr><th><?= app_escape($txt('Run', 'التشغيل')) ?></th><th><?= app_escape($txt('Employee', 'الموظف')) ?></th><th><?= app_escape($txt('Component', 'البند')) ?></th><th><?= app_escape($txt('Type', 'النوع')) ?></th><th><?= app_escape($txt('Amount', 'المبلغ')) ?></th><th><?= app_escape($txt('Account', 'الحساب')) ?></th><th><?= app_escape($txt('Cost Center', 'مركز التكلفة')) ?></th></tr></thead>
            <tbody>
              <?php foreach ($payrollItemRows as $row): ?>
                <tr>
                  <td><?= app_escape((string) ($row['run_number'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($row['employee_name'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($row['component_code'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($row['component_type'] ?? '')) ?></td>
                  <td><?= app_escape(app_money_format($row['amount'] ?? 0)) ?></td>
                  <td><?= app_escape((string) ($row['account_code'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($row['cost_center_code'] ?? '')) ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </section>
    <?php endif; ?>

    <?php if ($activeReport === 'overview' || $activeReport === 'contracts'): ?>
      <section class="table-card">
        <div class="table-header"><div><h3><?= app_escape($txt('Employee Contracts', 'عقود الموظفين')) ?></h3><div class="hint"><?= app_escape($fromDate) ?> - <?= app_escape($toDate) ?></div></div></div>
        <div class="table-wrap">
          <table class="data-table" style="min-width: 1100px;">
            <thead><tr><th><?= app_escape($txt('Contract', 'العقد')) ?></th><th><?= app_escape($txt('Employee', 'الموظف')) ?></th><th><?= app_escape($txt('Department', 'القسم')) ?></th><th><?= app_escape($txt('Job', 'الوظيفة')) ?></th><th><?= app_escape($txt('Type', 'النوع')) ?></th><th><?= app_escape($txt('Start', 'البداية')) ?></th><th><?= app_escape($txt('End', 'النهاية')) ?></th><th><?= app_escape($txt('Salary', 'الراتب')) ?></th><th><?= app_escape($txt('Allowance', 'البدل')) ?></th><th><?= app_escape($txt('Status', 'الحالة')) ?></th></tr></thead>
            <tbody>
              <?php foreach ($contractRows as $row): ?>
                <tr>
                  <td><?= app_escape((string) ($row['contract_number'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($row['employee_name'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($row['department_code'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($row['job_code'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($row['contract_type'] ?? '')) ?></td>
                  <td><?= app_escape(app_date_format((string) ($row['start_date'] ?? ''))) ?></td>
                  <td><?= app_escape(app_date_format((string) ($row['end_date'] ?? ''))) ?></td>
                  <td><?= app_escape(app_money_format($row['basic_salary'] ?? 0)) ?></td>
                  <td><?= app_escape(app_money_format($row['allowance'] ?? 0)) ?></td>
                  <td><?= app_escape((string) ($row['status'] ?? '')) ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </section>
    <?php endif; ?>

    <?php if ($activeReport === 'overview' || $activeReport === 'components'): ?>
      <section class="table-card">
        <div class="table-header"><div><h3><?= app_escape($txt('Salary Components', 'بنود الرواتب')) ?></h3><div class="hint"><?= app_escape($txt('Reusable earnings, allowances, deductions, and posting accounts.', 'تعريفات الرواتب والبدلات والاستقطاعات وحسابات التوجيه.')) ?></div></div></div>
        <div class="table-wrap">
          <table class="data-table" style="min-width: 980px;">
            <thead><tr><th><?= app_escape($txt('Code', 'الكود')) ?></th><th><?= app_escape($txt('Name', 'الاسم')) ?></th><th><?= app_escape($txt('Type', 'النوع')) ?></th><th><?= app_escape($txt('Calculation', 'الحساب')) ?></th><th><?= app_escape($txt('Default', 'الافتراضي')) ?></th><th><?= app_escape($txt('Percent', 'النسبة')) ?></th><th><?= app_escape($txt('Account', 'الحساب')) ?></th><th><?= app_escape($txt('Active', 'نشط')) ?></th></tr></thead>
            <tbody>
              <?php foreach ($componentRows as $row): ?>
                <tr>
                  <td><?= app_escape((string) ($row['component_code'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($row['component_name'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($row['component_type'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($row['calculation_type'] ?? '')) ?></td>
                  <td><?= app_escape(app_money_format($row['default_amount'] ?? 0)) ?></td>
                  <td><?= app_escape(app_money_format($row['percent_value'] ?? 0)) ?>%</td>
                  <td><?= app_escape((string) ($row['account_code'] ?? '')) ?></td>
                  <td><?= !empty($row['is_active']) ? 'Yes' : 'No' ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </section>
    <?php endif; ?>

    <?php if ($activeReport === 'overview'): ?>
      <section class="table-card">
        <div class="table-header"><div><h3><?= app_escape($txt('Department Cost Overview', 'نظرة تكلفة الأقسام')) ?></h3><div class="hint"><?= app_escape($txt('Estimated monthly net by department.', 'تقدير الصافي الشهري حسب القسم.')) ?></div></div></div>
        <div class="table-wrap">
          <table class="data-table">
            <thead><tr><th><?= app_escape($txt('Code', 'الكود')) ?></th><th><?= app_escape($txt('Department', 'القسم')) ?></th><th><?= app_escape($txt('Employees', 'الموظفون')) ?></th><th><?= app_escape($txt('Estimated Net', 'الصافي التقديري')) ?></th></tr></thead>
            <tbody>
              <?php foreach ($departmentRows as $row): ?>
                <tr><td><?= app_escape((string) ($row['department_code'] ?? '')) ?></td><td><?= app_escape((string) ($row['department_name'] ?? '')) ?></td><td><?= app_escape(number_format((int) ($row['employees_count'] ?? 0))) ?></td><td><?= app_escape(app_money_format($row['estimated_net'] ?? 0)) ?></td></tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </section>
    <?php endif; ?>
    </main>
  </div>
</div>
<script src="assets/app.js"></script>
</body>
</html>
