<?php
declare(strict_types=1);

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

$requestedCompanyId = (int) ($_REQUEST['company_id'] ?? 0);
$companyId = app_effective_company_id($requestedCompanyId > 0 ? $requestedCompanyId : null, true);
if ($companyId !== null && $companyId > 0) {
    app_set_context_company_id($companyId);
}

$companies = app_current_user_company_options();
$company = $companyId ? app_company_by_id((int) $companyId) : null;
$editId = (int) ($_GET['edit'] ?? 0);

$pageUrl = static function (array $extra = []) use ($companyId): string {
    $params = array_filter(
        $extra,
        static fn (mixed $value): bool => $value !== null && $value !== ''
    );
    if ($companyId !== null && $companyId > 0) {
        $params['company_id'] = $companyId;
    }
    return 'reports.php' . ($params ? ('?' . http_build_query($params)) : '');
};

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        app_verify_csrf();
        $action = (string) ($_POST['action'] ?? 'save');

        if ($action === 'save') {
            $templateId = (int) ($_POST['id'] ?? 0);
            $templateName = app_normalize_whitespace((string) ($_POST['template_name'] ?? ''));
            $defaultChartType = app_normalize_whitespace((string) ($_POST['chart_type'] ?? 'bar'));
            $moduleScope = app_normalize_whitespace((string) ($_POST['module_scope'] ?? 'multi-module'));
            $isActive = !empty($_POST['is_active']) ? 1 : 0;

            if ($templateName === '') {
                throw new RuntimeException('Template name is required.');
            }

            $titles = (array) ($_POST['section_title'] ?? []);
            $modules = (array) ($_POST['section_module'] ?? []);
            $labels = (array) ($_POST['section_label_column'] ?? []);
            $chartTypes = (array) ($_POST['section_chart_type'] ?? []);
            $styles = (array) ($_POST['section_style'] ?? []);
            $metricsBySection = (array) ($_POST['section_metrics'] ?? []);
            $topNs = (array) ($_POST['section_top_n'] ?? []);
            $sortModes = (array) ($_POST['section_sort_mode'] ?? []);
            $dateColumns = (array) ($_POST['section_date_column'] ?? []);
            $dateFroms = (array) ($_POST['section_date_from'] ?? []);
            $dateTos = (array) ($_POST['section_date_to'] ?? []);

            $sections = [];
            $totalSections = max(count($titles), count($modules), count($labels));
            for ($i = 0; $i < $totalSections; $i++) {
                $sectionTitle = app_normalize_whitespace((string) ($titles[$i] ?? ''));
                $sectionModule = app_normalize_whitespace((string) ($modules[$i] ?? ''));
                $sectionLabel = app_normalize_whitespace((string) ($labels[$i] ?? ''));
                $sectionChartType = app_normalize_whitespace((string) ($chartTypes[$i] ?? $defaultChartType));
                $sectionStyle = app_normalize_whitespace((string) ($styles[$i] ?? 'classic'));
                $sectionTopN = max(1, min(500, app_integer($topNs[$i] ?? 150)));
                $sectionSortMode = app_normalize_whitespace((string) ($sortModes[$i] ?? 'label_asc'));
                if (!in_array($sectionSortMode, ['label_asc', 'value_desc'], true)) {
                    $sectionSortMode = 'label_asc';
                }
                $sectionDateColumn = app_normalize_whitespace((string) ($dateColumns[$i] ?? ''));
                $sectionDateFrom = app_normalize_whitespace((string) ($dateFroms[$i] ?? ''));
                $sectionDateTo = app_normalize_whitespace((string) ($dateTos[$i] ?? ''));
                $sectionMetricsRaw = (array) ($metricsBySection[$i] ?? []);
                $sectionMetrics = [];
                foreach ($sectionMetricsRaw as $metric) {
                    $metric = app_normalize_whitespace((string) $metric);
                    if ($metric !== '') {
                        $sectionMetrics[] = $metric;
                    }
                }
                $sectionMetrics = array_values(array_unique($sectionMetrics));

                if ($sectionTitle === '' && $sectionModule === '' && $sectionLabel === '' && !$sectionMetrics) {
                    continue;
                }

                if ($sectionTitle === '' || $sectionModule === '' || $sectionLabel === '' || !$sectionMetrics) {
                    throw new RuntimeException('Each section requires title, module, label column, and at least one comparison column.');
                }

                $sections[] = [
                    'title' => $sectionTitle,
                    'module' => $sectionModule,
                    'label_column' => $sectionLabel,
                    'metric_columns' => $sectionMetrics,
                    'chart_type' => $sectionChartType !== '' ? $sectionChartType : 'bar',
                    'style' => $sectionStyle !== '' ? $sectionStyle : 'classic',
                    'top_n' => $sectionTopN,
                    'sort_mode' => $sectionSortMode,
                    'date_column' => $sectionDateColumn,
                    'date_from' => $sectionDateFrom,
                    'date_to' => $sectionDateTo,
                ];
            }

            if (!$sections) {
                throw new RuntimeException('Add at least one section before saving template.');
            }

            $configJson = json_encode(['sections' => $sections], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            if (!is_string($configJson)) {
                throw new RuntimeException('Failed to encode template sections.');
            }

            $payload = [
                'template_name' => $templateName,
                'module_scope' => $moduleScope,
                'chart_type' => $defaultChartType !== '' ? $defaultChartType : 'bar',
                'config_json' => $configJson,
                'is_active' => $isActive,
            ];

            $savedId = app_module_save('report_templates', $payload, $companyId, $templateId > 0 ? $templateId : null);
            app_flash('success', 'Report template saved successfully.');
            app_redirect($pageUrl(['edit' => $savedId]));
        }

        if ($action === 'delete') {
            $templateId = (int) ($_POST['id'] ?? 0);
            app_module_delete('report_templates', $templateId, $companyId);
            app_flash('success', 'Report template deleted successfully.');
            app_redirect($pageUrl());
        }

        if ($action === 'bulk_delete') {
            $templateIds = array_values(array_unique(array_filter(
                array_map('intval', (array) ($_POST['record_ids'] ?? [])),
                static fn (int $id): bool => $id > 0
            )));
            if (!$templateIds) {
                throw new RuntimeException(app_t('No records selected.'));
            }

            $pdo = app_pdo();
            $startedTransaction = false;
            try {
                if (!$pdo->inTransaction()) {
                    $pdo->beginTransaction();
                    $startedTransaction = true;
                }

                foreach ($templateIds as $templateId) {
                    app_module_delete('report_templates', $templateId, $companyId);
                }

                if ($startedTransaction && $pdo->inTransaction()) {
                    $pdo->commit();
                }
            } catch (Throwable $e) {
                if ($startedTransaction && $pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                throw $e;
            }

            app_flash('success', count($templateIds) . ' template(s) deleted successfully.');
            app_redirect($pageUrl());
        }
    } catch (Throwable $e) {
        app_flash('error', $e->getMessage());
        app_redirect($pageUrl(['edit' => $editId > 0 ? $editId : null]));
    }
}

$templates = app_module_list('report_templates', $companyId, '');
$editing = $editId > 0 ? app_module_find('report_templates', $editId, $companyId) : null;
if (!$editing && !empty($templates[0])) {
    $editing = $templates[0];
}
$templateSections = $editing ? app_report_template_sections($editing) : [];
if (!$templateSections) {
    $templateSections = [[
        'title' => 'Revenue vs Collection',
        'module' => 'sales_invoices',
        'label_column' => 'invoice_date',
        'metric_columns' => ['grand_total', 'paid_amount'],
        'chart_type' => 'bar',
        'style' => 'classic',
        'top_n' => 25,
        'sort_mode' => 'label_asc',
        'date_column' => '',
        'date_from' => '',
        'date_to' => '',
    ]];
}

$catalog = [];
foreach (app_visible_modules() as $module) {
    $slug = (string) ($module['slug'] ?? '');
    if ($slug === 'report_templates') {
        continue;
    }
    try {
        $columnsData = app_module_table_columns($slug);
        $allColumns = [];
        foreach ($columnsData as $column) {
            $name = (string) ($column['COLUMN_NAME'] ?? '');
            if ($name !== '' && $name !== 'id' && $name !== 'company_id') {
                $allColumns[] = $name;
            }
        }
        $dateColumns = [];
        foreach ($columnsData as $column) {
            $name = (string) ($column['COLUMN_NAME'] ?? '');
            $type = strtolower((string) ($column['DATA_TYPE'] ?? ''));
            if ($name !== '' && in_array($type, ['date', 'datetime', 'timestamp'], true)) {
                $dateColumns[] = $name;
            }
        }
        $catalog[$slug] = [
            'title' => (string) ($module['title'] ?? $slug),
            'columns' => array_values(array_unique($allColumns)),
            'numeric_columns' => app_module_numeric_columns($slug),
            'date_columns' => array_values(array_unique($dateColumns)),
        ];
    } catch (Throwable) {
        $catalog[$slug] = [
            'title' => (string) ($module['title'] ?? $slug),
            'columns' => [],
            'numeric_columns' => [],
            'date_columns' => [],
        ];
    }
}
?>
<!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(app_t((string) app_config('app_name'))) ?> - <?= app_escape(app_t('Report Designer')) ?></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('reports', null, $companyId) ?>

  <header class="header">
    <div class="header-side right">
      <div class="header-title"><?= app_escape(app_t('Report Designer')) ?></div>
      <div class="header-subtitle"><?= app_escape(app_t('Build sections and multi-column comparisons per report template.')) ?></div>
    </div>
    <div class="header-center">
      <img src="<?= app_escape(app_logo_path_for_header($company)) ?>" alt="Logo" class="school-logo">
    </div>
    <div class="header-side left">
      <div class="header-title"><?= app_escape((string) (app_current_user()['full_name'] ?? app_current_username())) ?></div>
      <div class="header-subtitle"><a href="index.php<?= $companyId ? '?company_id=' . (int) $companyId : '' ?>"><?= app_escape(app_t('Dashboard')) ?></a> &bull; <a href="logout.php"><?= app_escape(app_t('Logout')) ?></a></div>
    </div>
  </header>

  <div class="date-bar">
    <div class="date-item"><?= app_escape(app_t('Date :')) ?> <span><?= app_escape(date('Y-m-d')) ?></span></div>
    <div class="date-item"><?= app_escape(app_t('Page :')) ?> <span><?= app_escape(app_t('Report Designer')) ?></span></div>
    <div class="date-author"><?= app_escape(app_t('Prepared by :')) ?> <?= app_escape((string) (app_current_user()['full_name'] ?? app_current_username())) ?></div>
  </div>

  <?= app_back_button_html('Back') ?>

  <div class="container">
    <div class="flash-stack">
      <?php if ($success = app_flash('success')): ?>
        <div class="alert success"><?= app_escape($success) ?></div>
      <?php endif; ?>
      <?php if ($error = app_flash('error')): ?>
        <div class="alert error"><?= app_escape($error) ?></div>
      <?php endif; ?>
    </div>

    <section class="panel screen-only context-switch-panel">
      <div class="section-heading">
        <h3>Company Context</h3>
        <span>Select company before designing reports</span>
      </div>
      <form method="get" class="form-grid two">
        <?php if (app_is_admin()): ?>
          <div class="field">
            <label for="company_id">Company</label>
            <select id="company_id" name="company_id" data-auto-submit>
              <?php foreach ($companies as $companyRow): ?>
                <option value="<?= (int) $companyRow['id'] ?>" <?= (int) $companyRow['id'] === (int) $companyId ? 'selected' : '' ?>>
                  <?= app_escape((string) $companyRow['name']) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
        <?php else: ?>
          <div class="field">
            <label>Company</label>
            <input type="text" value="<?= app_escape((string) ($company['name'] ?? 'N/A')) ?>" readonly>
          </div>
        <?php endif; ?>
      </form>
    </section>

    <section class="panel screen-only">
      <div class="section-heading">
        <h3><?= $editing ? 'Edit Template' : 'Create Template' ?></h3>
        <span>Add multiple sections and comparison columns per section</span>
      </div>
      <form method="post" class="stacked">
        <?= app_csrf_field() ?>
        <input type="hidden" name="action" value="save">
        <input type="hidden" name="id" value="<?= (int) ($editing['id'] ?? 0) ?>">
        <?php if ($companyId !== null): ?>
          <input type="hidden" name="company_id" value="<?= (int) $companyId ?>">
        <?php endif; ?>

        <div class="form-grid four">
          <div class="field">
            <label for="template_name">Template Name</label>
            <input id="template_name" name="template_name" type="text" required value="<?= app_escape((string) ($editing['template_name'] ?? '')) ?>">
          </div>
          <div class="field">
            <label for="module_scope">Scope</label>
            <input id="module_scope" name="module_scope" type="text" value="<?= app_escape((string) ($editing['module_scope'] ?? 'multi-module')) ?>">
          </div>
          <div class="field">
            <label for="chart_type">Default Chart Type</label>
            <select id="chart_type" name="chart_type">
              <?php foreach (['bar' => 'Bar', 'line' => 'Line', 'pie' => 'Pie', 'doughnut' => 'Doughnut'] as $key => $label): ?>
                <option value="<?= app_escape($key) ?>" <?= (string) ($editing['chart_type'] ?? 'bar') === $key ? 'selected' : '' ?>><?= app_escape($label) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="field">
            <label style="display:flex;align-items:center;gap:8px;">
              <input type="checkbox" name="is_active" value="1" <?= !isset($editing['is_active']) || (int) ($editing['is_active'] ?? 1) === 1 ? 'checked' : '' ?>>
              Active template
            </label>
          </div>
        </div>

        <div class="section-heading" style="margin-top:8px;">
          <h3>Template Sections</h3>
          <span>Each section can compare one item against many metrics</span>
        </div>
        <div id="sectionsBuilder" class="design-builder-grid"></div>

        <div class="form-actions">
          <button class="btn btn-secondary" type="button" id="addSectionBtn">Add Section</button>
          <button class="btn btn-primary" type="submit">Save Template</button>
          <?php if (!empty($editing['id'])): ?>
            <a class="btn btn-ghost" href="<?= app_escape($pageUrl()) ?>">New Template</a>
          <?php endif; ?>
        </div>
      </form>
    </section>

    <section class="table-card" data-bulk-scope>
      <div class="table-header">
        <div>
          <h3>Saved Templates</h3>
          <div class="hint"><?= app_escape(app_t(number_format(count($templates)) . ' template(s)')) ?></div>
        </div>
        <?php if ($templates): ?>
          <div class="bulk-actions screen-only">
            <button class="btn btn-secondary" type="button" data-bulk-select-mode><?= app_escape(app_t('Select')) ?></button>
            <button class="btn btn-secondary" type="button" data-bulk-select-all><?= app_escape(app_t('Select All')) ?></button>
            <button class="btn btn-ghost" type="button" data-bulk-clear><?= app_escape(app_t('Clear Selection')) ?></button>
            <button class="btn btn-danger" type="submit" form="reportTemplatesBulkDeleteForm" data-bulk-delete disabled><?= app_escape(app_t('Delete Selected')) ?></button>
            <span class="bulk-count" data-bulk-count>0 <?= app_escape(app_t('selected')) ?></span>
          </div>
        <?php endif; ?>
      </div>
      <?php if (!$templates): ?>
        <div class="empty-state">No templates yet for this company.</div>
      <?php else: ?>
        <form id="reportTemplatesBulkDeleteForm" method="post" class="bulk-delete-form" data-bulk-delete-form data-confirm-message="<?= app_escape(app_t('Delete selected records?')) ?>">
          <?= app_csrf_field() ?>
          <input type="hidden" name="action" value="bulk_delete">
          <?php if ($companyId !== null): ?>
            <input type="hidden" name="company_id" value="<?= (int) $companyId ?>">
          <?php endif; ?>
        </form>
        <div class="table-wrap">
          <table class="data-table" style="min-width: 980px;">
            <thead>
              <tr>
                <th class="bulk-select-cell print-hide"><?= app_escape(app_t('Select')) ?></th>
                <th>Name</th>
                <th>Scope</th>
                <th>Default Chart</th>
                <th>Status</th>
                <th>Created</th>
                <th class="print-hide">Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($templates as $template): ?>
                <tr>
                  <td class="bulk-select-cell print-hide">
                    <input
                      type="checkbox"
                      name="record_ids[]"
                      value="<?= (int) $template['id'] ?>"
                      form="reportTemplatesBulkDeleteForm"
                      data-bulk-checkbox
                    >
                  </td>
                  <td><?= app_escape((string) ($template['template_name'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($template['module_scope'] ?? '')) ?></td>
                  <td><?= app_escape((string) ($template['chart_type'] ?? '')) ?></td>
                  <td><?= (int) ($template['is_active'] ?? 0) === 1 ? '<span class="badge badge-green">Active</span>' : '<span class="badge badge-red">Inactive</span>' ?></td>
                  <td><?= app_escape(app_date_format((string) ($template['created_at'] ?? ''))) ?></td>
                  <td class="print-hide">
                    <div class="actions">
                      <a class="icon-btn" href="<?= app_escape($pageUrl(['edit' => (int) $template['id']])) ?>">Edit</a>
                      <form method="post" onsubmit="return confirm('Delete this template?');">
                        <?= app_csrf_field() ?>
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" value="<?= (int) $template['id'] ?>">
                        <?php if ($companyId !== null): ?>
                          <input type="hidden" name="company_id" value="<?= (int) $companyId ?>">
                        <?php endif; ?>
                        <button class="icon-btn danger" type="submit">Delete</button>
                      </form>
                    </div>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </section>

    <div class="footer">
      <?= app_escape((string) app_config('app_name')) ?> &bull; <?= app_escape(app_t('Report Designer for section-based multi-metric comparisons.')) ?>
    </div>
  </div>

  <button id="floatingPrintBtn" class="floating-print-btn screen-only" type="button"><?= app_escape(app_t('Print')) ?></button>
</div>

<script>
const reportCatalog = <?= json_encode($catalog, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const initialSections = <?= json_encode($templateSections, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const builder = document.getElementById('sectionsBuilder');
const addSectionBtn = document.getElementById('addSectionBtn');
const reportText = <?= json_encode([
  'section' => app_t('Section'),
  'define_columns' => app_t('Define one item and multiple comparison columns'),
  'section_title' => app_t('Section Title'),
  'module' => app_t('Module'),
  'label_column' => app_t('Label Column'),
  'chart_type' => app_t('Chart Type'),
  'section_style' => app_t('Section Style'),
  'top_n_rows' => app_t('Top N Rows'),
  'sort_mode' => app_t('Sort Mode'),
  'date_column_optional' => app_t('Date Column (Optional)'),
  'date_from_optional' => app_t('Date From (Optional)'),
  'date_to_optional' => app_t('Date To (Optional)'),
  'comparison_columns' => app_t('Comparison Columns (choose one or more)'),
  'multi_select_help' => app_t('Use Ctrl/Cmd click to select multiple metrics for this section.'),
  'remove_section' => app_t('Remove Section'),
  'any_date_column' => app_t('Any date column'),
  'classic' => app_t('Classic'),
  'glass' => app_t('Glass'),
  'sunset' => app_t('Sunset'),
  'forest' => app_t('Forest'),
  'royal' => app_t('Royal'),
  'bar' => app_t('Bar'),
  'line' => app_t('Line'),
  'pie' => app_t('Pie'),
  'doughnut' => app_t('Doughnut'),
  'label_az' => app_t('Label A-Z'),
  'top_by_first_metric' => app_t('Top by first metric'),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?: '{}' ?>;

function reportT(key) {
  return reportText[key] || key;
}

const styleOptions = [
  ['classic', reportT('classic')],
  ['glass', reportT('glass')],
  ['sunset', reportT('sunset')],
  ['forest', reportT('forest')],
  ['royal', reportT('royal')]
];
const chartOptions = [
  ['bar', reportT('bar')],
  ['line', reportT('line')],
  ['pie', reportT('pie')],
  ['doughnut', reportT('doughnut')]
];
const sortOptions = [
  ['label_asc', reportT('label_az')],
  ['value_desc', reportT('top_by_first_metric')]
];

function optionHtml(value, label, selectedValue) {
  const selected = String(value) === String(selectedValue) ? ' selected' : '';
  return `<option value="${value}"${selected}>${label}</option>`;
}

function moduleOptions(selectedModule) {
  return Object.entries(reportCatalog)
    .map(([slug, item]) => optionHtml(slug, item.title || slug, selectedModule))
    .join('');
}

function syncSectionFields(sectionEl) {
  const moduleSelect = sectionEl.querySelector('[data-section-module]');
  const labelSelect = sectionEl.querySelector('[data-section-label]');
  const metricsSelect = sectionEl.querySelector('[data-section-metrics]');
  const dateColumnSelect = sectionEl.querySelector('[data-section-date-column]');
  const sectionIndex = Number(sectionEl.dataset.sectionIndex || 0);

  const selectedModule = moduleSelect.value;
  const moduleInfo = reportCatalog[selectedModule] || { columns: [], numeric_columns: [], date_columns: [] };
  const currentLabel = labelSelect.dataset.currentValue || '';
  const currentMetrics = (metricsSelect.dataset.currentValues || '').split('|').filter(Boolean);
  const currentDateColumn = dateColumnSelect ? (dateColumnSelect.dataset.currentValue || '') : '';

  labelSelect.innerHTML = moduleInfo.columns
    .map((col) => optionHtml(col, col, currentLabel))
    .join('');

  metricsSelect.innerHTML = moduleInfo.numeric_columns
    .map((col) => {
      const selected = currentMetrics.includes(col) ? ' selected' : '';
      return `<option value="${col}"${selected}>${col}</option>`;
    })
    .join('');

  if (dateColumnSelect) {
    const dateOptions = [`<option value="">${reportT('any_date_column')}</option>`]
      .concat((moduleInfo.date_columns || []).map((col) => optionHtml(col, col, currentDateColumn)));
    dateColumnSelect.innerHTML = dateOptions.join('');
  }

  metricsSelect.name = `section_metrics[${sectionIndex}][]`;
}

function createSection(index, section) {
  const data = Object.assign({
    title: '',
    module: Object.keys(reportCatalog)[0] || '',
    label_column: '',
    metric_columns: [],
    chart_type: 'bar',
    style: 'classic',
    top_n: 25,
    sort_mode: 'label_asc',
    date_column: '',
    date_from: '',
    date_to: ''
  }, section || {});

  const sectionEl = document.createElement('div');
  sectionEl.className = `design-section-card design-style-${data.style || 'classic'}`;
  sectionEl.dataset.sectionIndex = String(index);
  sectionEl.innerHTML = `
    <div class="section-heading">
      <h3>${reportT('section')} ${index + 1}</h3>
      <span>${reportT('define_columns')}</span>
    </div>
    <div class="form-grid four">
      <div class="field">
        <label>${reportT('section_title')}</label>
        <input type="text" name="section_title[]" value="${(data.title || '').replace(/"/g, '&quot;')}" required>
      </div>
      <div class="field">
        <label>${reportT('module')}</label>
        <select name="section_module[]" data-section-module>
          ${moduleOptions(data.module)}
        </select>
      </div>
      <div class="field">
        <label>${reportT('label_column')}</label>
        <select name="section_label_column[]" data-section-label data-current-value="${data.label_column || ''}"></select>
      </div>
      <div class="field">
        <label>${reportT('chart_type')}</label>
        <select name="section_chart_type[]">
          ${chartOptions.map(([v, l]) => optionHtml(v, l, data.chart_type)).join('')}
        </select>
      </div>
      <div class="field">
        <label>${reportT('section_style')}</label>
        <select name="section_style[]">
          ${styleOptions.map(([v, l]) => optionHtml(v, l, data.style)).join('')}
        </select>
      </div>
      <div class="field">
        <label>${reportT('top_n_rows')}</label>
        <input type="number" min="1" max="500" name="section_top_n[]" value="${Number(data.top_n || 25)}">
      </div>
      <div class="field">
        <label>${reportT('sort_mode')}</label>
        <select name="section_sort_mode[]">
          ${sortOptions.map(([v, l]) => optionHtml(v, l, data.sort_mode || 'label_asc')).join('')}
        </select>
      </div>
      <div class="field">
        <label>${reportT('date_column_optional')}</label>
        <select name="section_date_column[]" data-section-date-column data-current-value="${data.date_column || ''}"></select>
      </div>
      <div class="field">
        <label>${reportT('date_from_optional')}</label>
        <input type="date" name="section_date_from[]" value="${data.date_from || ''}">
      </div>
      <div class="field">
        <label>${reportT('date_to_optional')}</label>
        <input type="date" name="section_date_to[]" value="${data.date_to || ''}">
      </div>
      <div class="field" style="grid-column: span 3;">
        <label>${reportT('comparison_columns')}</label>
        <select multiple size="6" data-section-metrics data-current-values="${(data.metric_columns || []).join('|')}"></select>
        <div class="field-help">${reportT('multi_select_help')}</div>
      </div>
    </div>
    <div class="form-actions">
      <button type="button" class="btn btn-danger" data-remove-section>${reportT('remove_section')}</button>
    </div>
  `;

  const moduleSelect = sectionEl.querySelector('[data-section-module]');
  moduleSelect.addEventListener('change', () => {
    const labelSelect = sectionEl.querySelector('[data-section-label]');
    const metricsSelect = sectionEl.querySelector('[data-section-metrics]');
    const dateColumnSelect = sectionEl.querySelector('[data-section-date-column]');
    labelSelect.dataset.currentValue = '';
    metricsSelect.dataset.currentValues = '';
    if (dateColumnSelect) {
      dateColumnSelect.dataset.currentValue = '';
    }
    syncSectionFields(sectionEl);
  });

  sectionEl.querySelector('[data-remove-section]').addEventListener('click', () => {
    sectionEl.remove();
    rebuildIndices();
  });

  const styleSelect = sectionEl.querySelector('select[name="section_style[]"]');
  styleSelect.addEventListener('change', () => {
    sectionEl.className = `design-section-card design-style-${styleSelect.value || 'classic'}`;
  });

  builder.appendChild(sectionEl);
  syncSectionFields(sectionEl);
}

function rebuildIndices() {
  const sections = Array.from(builder.querySelectorAll('.design-section-card'));
  sections.forEach((sectionEl, index) => {
    sectionEl.dataset.sectionIndex = String(index);
    const titleEl = sectionEl.querySelector('.section-heading h3');
    if (titleEl) titleEl.textContent = `${reportT('section')} ${index + 1}`;
    const metricsSelect = sectionEl.querySelector('[data-section-metrics]');
    if (metricsSelect) metricsSelect.name = `section_metrics[${index}][]`;
  });
}

function addSection(sectionData = null) {
  const index = builder.querySelectorAll('.design-section-card').length;
  createSection(index, sectionData);
}

if (Array.isArray(initialSections) && initialSections.length > 0) {
  initialSections.forEach((section) => addSection(section));
} else {
  addSection();
}

if (addSectionBtn) {
  addSectionBtn.addEventListener('click', () => addSection());
}
</script>
<script src="assets/app.js"></script>
</body>
</html>


