<?php
declare(strict_types=1);

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

$bootstrapError = app_bootstrap_error();
if ($bootstrapError !== null) {
    ?>
    <!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('Bootstrap Error')) ?></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>
      <main class="auth-shell">
        <section class="auth-card" style="grid-template-columns:1fr;">
          <div class="auth-hero">
            <img src="assets/logo.svg" alt="Logo" class="auth-logo">
            <h1>System bootstrap failed</h1>
            <p>The app could not connect to MySQL or run migrations.</p>
            <div class="auth-meta">
              <span class="chip"><?= app_escape($bootstrapError) ?></span>
            </div>
          </div>
        </section>
      </main>
    </body>
    </html>
    <?php
    exit;
}

$requestedCompanyId = (int) ($_GET['company_id'] ?? 0);
$companyId = app_effective_company_id($requestedCompanyId > 0 ? $requestedCompanyId : null, false);
$companies = app_current_user_company_options();
if ($companyId === null && !empty($companies[0]['id'])) {
    $companyId = (int) $companies[0]['id'];
}
if ($companyId !== null && $companyId > 0) {
    app_set_context_company_id($companyId);
}

$company = $companyId ? app_company_by_id((int) $companyId) : null;
$counts = app_module_counts($companyId);
$visibleModules = array_values(array_filter(
    app_visible_modules(),
    static fn (array $item): bool => ((string) ($item['slug'] ?? '') !== 'report_templates')
));

$totalRows = array_sum($counts);
$activeUsers = (int) ($counts['users'] ?? 0);
$totalCompanies = (int) ($counts['companies'] ?? 0);
$reportTemplates = app_module_list('report_templates', $companyId, '');
$selectedTemplateId = (int) ($_GET['template_id'] ?? 0);
$dashboardFromDate = app_sanitize_date((string) ($_GET['from_date'] ?? date('Y-01-01')), date('Y-01-01'));
$dashboardToDate = app_sanitize_date((string) ($_GET['to_date'] ?? date('Y-m-d')), date('Y-m-d'));
if ($dashboardFromDate > $dashboardToDate) {
    [$dashboardFromDate, $dashboardToDate] = [$dashboardToDate, $dashboardFromDate];
}
$activeTemplate = null;
foreach ($reportTemplates as $template) {
    if ((int) ($template['id'] ?? 0) === $selectedTemplateId) {
        $activeTemplate = $template;
        break;
    }
}
if (!$activeTemplate && !empty($reportTemplates[0])) {
    $activeTemplate = $reportTemplates[0];
}
$sections = $activeTemplate ? app_report_template_sections($activeTemplate) : [];
$templateId = (int) ($activeTemplate['id'] ?? 0);
$dashboardPrintTitle = $activeTemplate
    ? (string) ($activeTemplate['template_name'] ?? app_t('Dashboard Report'))
    : app_t('Dashboard Report');
$dashboardExportQuery = $_GET;
if ($companyId !== null && $companyId > 0) {
    $dashboardExportQuery['company_id'] = $companyId;
}
$dashboardExportQuery['template_id'] = $templateId;
$dashboardExportQuery['from_date'] = $dashboardFromDate;
$dashboardExportQuery['to_date'] = $dashboardToDate;
$dashboardExportQuery['export'] = 'xlsx';
$dashboardExportUrl = 'index.php?' . http_build_query($dashboardExportQuery);

function dashboard_color(int $index): string
{
    $colors = ['#2563eb', '#14b8a6', '#f59e0b', '#ef4444', '#64748b', '#0ea5e9', '#84cc16', '#8b5cf6'];
    return $colors[$index % count($colors)];
}

function dashboard_conic_gradient(array $values): string
{
    $total = 0.0;
    foreach ($values as $value) {
        $total += max(0, app_number($value));
    }
    if ($total <= 0) {
        return 'conic-gradient(#e6e9f3 0deg 360deg)';
    }

    $start = 0.0;
    $parts = [];
    foreach ($values as $index => $value) {
        $amount = max(0, app_number($value));
        $deg = ($amount / $total) * 360;
        $end = $start + $deg;
        $parts[] = dashboard_color($index) . ' ' . number_format($start, 2, '.', '') . 'deg ' . number_format($end, 2, '.', '') . 'deg';
        $start = $end;
    }
    return 'conic-gradient(' . implode(', ', $parts) . ')';
}

function dashboard_sort_dataset_ascending(array $dataset): array
{
    $labels = (array) ($dataset['labels'] ?? []);
    $series = (array) ($dataset['series'] ?? []);
    if (!$labels || !$series || empty($series[0]['values'])) {
        return $dataset;
    }

    $order = array_keys($labels);
    usort(
        $order,
        static fn (int $a, int $b): int => app_number($series[0]['values'][$a] ?? 0) <=> app_number($series[0]['values'][$b] ?? 0)
    );

    $sortedLabels = [];
    foreach ($order as $index) {
        $sortedLabels[] = $labels[$index] ?? '';
    }

    foreach ($series as &$seriesItem) {
        $oldValues = (array) ($seriesItem['values'] ?? []);
        $newValues = [];
        foreach ($order as $index) {
            $newValues[] = app_number($oldValues[$index] ?? 0);
        }
        $seriesItem['values'] = $newValues;
    }
    unset($seriesItem);

    return ['labels' => $sortedLabels, 'series' => $series];
}

function render_template_section(array $section, ?int $companyId, string $fromDate = '', string $toDate = ''): string
{
    if (app_normalize_whitespace((string) ($section['date_column'] ?? '')) !== '') {
        if ($fromDate !== '') {
            $section['date_from'] = $fromDate;
        }
        if ($toDate !== '') {
            $section['date_to'] = $toDate;
        }
    }
    $dataset = app_report_series_for_section($section, $companyId);
    $dataset = dashboard_sort_dataset_ascending($dataset);
    $labels = $dataset['labels'] ?? [];
    $series = $dataset['series'] ?? [];
    $title = app_normalize_whitespace((string) ($section['title'] ?? 'Report Section'));
    $chartType = strtolower(app_normalize_whitespace((string) ($section['chart_type'] ?? 'bar')));
    if (!in_array($chartType, ['bar', 'line', 'pie', 'doughnut'], true)) {
        $chartType = 'bar';
    }
    $badge = strtoupper($chartType) . ' / ' . app_escape((string) ($section['module'] ?? ''));

    if (!$labels || !$series) {
        return '<div class="chart-card"><div class="chart-title"><span>' . app_escape($title) . '</span><span class="chart-badge">' . $badge . '</span></div><div class="chart-empty">No data available for this section.</div></div>';
    }

    $max = 0.0;
    $metricTotals = [];
    foreach ($series as $seriesItem) {
        $metricTotal = 0.0;
        foreach ((array) ($seriesItem['values'] ?? []) as $value) {
            $numericValue = app_number($value);
            $metricTotal += $numericValue;
            $max = max($max, $numericValue);
        }
        $metricTotals[] = $metricTotal;
    }
    if ($max <= 0) {
        $max = 1;
    }

    $rowCount = count($labels);

    ob_start();
    ?>
    <div class="chart-card">
      <div class="chart-title">
        <span><?= app_escape($title) ?></span>
        <span class="chart-badge"><?= $badge ?></span>
      </div>
      <div class="section-summary-grid">
        <div class="section-summary-tile">
          <div class="summary-label">Rows</div>
          <div class="summary-value"><?= app_escape(number_format($rowCount)) ?></div>
        </div>
        <?php foreach ($series as $seriesIndex => $seriesItem): ?>
          <div class="section-summary-tile">
            <div class="summary-label"><?= app_escape((string) ($seriesItem['name'] ?? ('Series ' . ($seriesIndex + 1)))) ?></div>
            <div class="summary-value"><?= app_escape(app_money_format($metricTotals[$seriesIndex] ?? 0)) ?></div>
          </div>
        <?php endforeach; ?>
      </div>

      <div class="legend-row comparison-legend">
        <?php foreach ($series as $index => $seriesItem): ?>
          <span class="legend-item">
            <span class="legend-dot" style="background: <?= app_escape(dashboard_color($index)) ?>;"></span>
            <?= app_escape((string) ($seriesItem['name'] ?? ('Series ' . ($index + 1)))) ?>
          </span>
        <?php endforeach; ?>
      </div>

      <?php if ($chartType === 'line'): ?>
        <?php
          $svgWidth = 700;
          $svgHeight = 240;
          $padding = 20;
          $plotWidth = $svgWidth - ($padding * 2);
          $plotHeight = $svgHeight - ($padding * 2);
          $labelsCount = count($labels);
        ?>
        <div class="line-chart-wrap">
          <svg viewBox="0 0 <?= $svgWidth ?> <?= $svgHeight ?>" class="line-chart-svg" role="img" aria-label="Line chart for <?= app_escape($title) ?>">
            <?php for ($i = 0; $i <= 4; $i++): ?>
              <?php $y = $padding + (($plotHeight / 4) * $i); ?>
              <line x1="<?= $padding ?>" y1="<?= app_escape(number_format($y, 2, '.', '')) ?>" x2="<?= $svgWidth - $padding ?>" y2="<?= app_escape(number_format($y, 2, '.', '')) ?>" stroke="rgba(45,10,107,0.12)" stroke-width="1"></line>
            <?php endfor; ?>
            <?php foreach ($series as $seriesIndex => $seriesItem): ?>
              <?php
                $points = [];
                foreach ((array) ($seriesItem['values'] ?? []) as $valueIndex => $value) {
                    $x = $padding + ($labelsCount <= 1 ? ($plotWidth / 2) : (($valueIndex / max(1, $labelsCount - 1)) * $plotWidth));
                    $y = $padding + ($plotHeight - ((app_number($value) / $max) * $plotHeight));
                    $points[] = number_format($x, 2, '.', '') . ',' . number_format($y, 2, '.', '');
                }
              ?>
              <?php if ($points): ?>
                <polyline fill="none" stroke="<?= app_escape(dashboard_color($seriesIndex)) ?>" stroke-width="3" points="<?= app_escape(implode(' ', $points)) ?>"></polyline>
                <?php foreach ($points as $point): ?>
                  <?php [$cx, $cy] = explode(',', $point); ?>
                  <circle cx="<?= app_escape($cx) ?>" cy="<?= app_escape($cy) ?>" r="3" fill="<?= app_escape(dashboard_color($seriesIndex)) ?>"></circle>
                <?php endforeach; ?>
              <?php endif; ?>
            <?php endforeach; ?>
          </svg>
          <div class="line-axis-labels">
            <?php foreach ($labels as $label): ?>
              <span><?= app_escape((string) $label) ?></span>
            <?php endforeach; ?>
          </div>
        </div>
      <?php elseif ($chartType === 'pie' || $chartType === 'doughnut'): ?>
        <?php
          $primarySeries = $series[0] ?? ['name' => 'Series 1', 'values' => []];
          $sliceValues = array_map(static fn (mixed $value): float => max(0, app_number($value)), (array) ($primarySeries['values'] ?? []));
          $sliceTotal = max(0, array_sum($sliceValues));
          $gradient = dashboard_conic_gradient($sliceValues);
        ?>
        <div class="section-donut-wrap">
          <div class="section-donut<?= $chartType === 'pie' ? ' as-pie' : '' ?>" style="background: <?= app_escape($gradient) ?>;">
            <div class="section-donut-center">
              <div class="big"><?= app_escape(app_money_format($sliceTotal)) ?></div>
              <div class="small"><?= app_escape((string) ($primarySeries['name'] ?? 'Series')) ?></div>
            </div>
          </div>
          <div class="bar-list">
            <?php foreach ($labels as $labelIndex => $label): ?>
              <?php
                $value = $sliceValues[$labelIndex] ?? 0;
                $percent = $sliceTotal > 0 ? (($value / $sliceTotal) * 100) : 0;
              ?>
              <div class="bar-row">
                <div class="bar-label"><?= app_escape((string) $label) ?></div>
                <div class="bar-track">
                  <span class="bar-fill" style="width: <?= app_escape(number_format(max(3, $percent), 1, '.', '')) ?>%; background: <?= app_escape(dashboard_color($labelIndex)) ?>;"></span>
                </div>
                <div class="bar-value"><?= app_escape(app_money_format($value)) ?></div>
              </div>
            <?php endforeach; ?>
          </div>
        </div>
      <?php else: ?>
        <div class="comparison-list">
          <?php foreach ($labels as $labelIndex => $label): ?>
            <div class="comparison-row">
              <div class="comparison-row-label"><?= app_escape((string) $label) ?></div>
              <div class="comparison-bars">
                <?php foreach ($series as $seriesIndex => $seriesItem): ?>
                  <?php $value = app_number($seriesItem['values'][$labelIndex] ?? 0); ?>
                  <?php $width = max(3, (($value / $max) * 100)); ?>
                  <div class="comparison-bar-row">
                    <div class="comparison-track">
                      <span class="comparison-fill" style="width: <?= app_escape(number_format($width, 1, '.', '')) ?>%; background: linear-gradient(90deg, <?= app_escape(dashboard_color($seriesIndex)) ?>, <?= app_escape(dashboard_color($seriesIndex + 1)) ?>);"></span>
                    </div>
                    <div class="comparison-value"><?= app_escape(app_money_format($value)) ?></div>
                  </div>
                <?php endforeach; ?>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>

      <div class="table-wrap section-detail-table">
        <table class="data-table" style="min-width: 760px;">
          <thead>
            <tr>
              <th>Label</th>
              <?php foreach ($series as $seriesItem): ?>
                <th><?= app_escape((string) ($seriesItem['name'] ?? 'Metric')) ?></th>
              <?php endforeach; ?>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($labels as $labelIndex => $label): ?>
              <tr>
                <td><?= app_escape((string) $label) ?></td>
                <?php foreach ($series as $seriesItem): ?>
                  <td><?= app_escape(app_money_format($seriesItem['values'][$labelIndex] ?? 0)) ?></td>
                <?php endforeach; ?>
              </tr>
            <?php endforeach; ?>
          </tbody>
          <tfoot>
            <tr>
              <th>Total</th>
              <?php foreach ($metricTotals as $metricTotal): ?>
                <th><?= app_escape(app_money_format($metricTotal)) ?></th>
              <?php endforeach; ?>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
    <?php
    return (string) ob_get_clean();
}

if (app_normalize_whitespace((string) ($_GET['export'] ?? '')) === 'xlsx') {
    $companyName = (string) ($company['name'] ?? 'N/A');
    $templateName = (string) ($activeTemplate['template_name'] ?? 'Designed Report');
    $preparedBy = (string) (app_current_user()['full_name'] ?? app_current_username());
    $sheets = [];

    foreach ($sections as $sectionIndex => $section) {
        if (app_normalize_whitespace((string) ($section['date_column'] ?? '')) !== '') {
            $section['date_from'] = $dashboardFromDate;
            $section['date_to'] = $dashboardToDate;
        }
        $dataset = dashboard_sort_dataset_ascending(app_report_series_for_section($section, $companyId));
        $labels = (array) ($dataset['labels'] ?? []);
        $series = (array) ($dataset['series'] ?? []);
        $title = app_normalize_whitespace((string) ($section['title'] ?? ('Report Section ' . ($sectionIndex + 1))));

        $rows = [
            app_xlsx_row([$title], 'title'),
            ['Company', $companyName],
            ['Template', $templateName],
            ['From Date', $dashboardFromDate],
            ['To Date', $dashboardToDate],
            ['Prepared By', $preparedBy],
            ['Generated At', date('Y-m-d H:i')],
            [],
        ];

        $header = ['Label'];
        foreach ($series as $seriesItem) {
            $header[] = (string) ($seriesItem['name'] ?? 'Metric');
        }
        $rows[] = app_xlsx_row($header, 'header');

        $metricTotals = array_fill(0, count($series), 0.0);
        foreach ($labels as $labelIndex => $label) {
            $row = [(string) $label];
            foreach ($series as $seriesIndex => $seriesItem) {
                $value = app_number($seriesItem['values'][$labelIndex] ?? 0);
                $metricTotals[$seriesIndex] += $value;
                $row[] = $value;
            }
            $rows[] = $row;
        }
        $rows[] = app_xlsx_row(array_merge(['Total'], $metricTotals), 'total');
        $sheets[] = ['title' => $title, 'rows' => $rows];
    }

    app_export_xlsx('designed-report-' . date('Ymd-His') . '.xlsx', $sheets);
}
?>
<!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('Dashboard')) ?></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('dashboard', null, $companyId) ?>

  <header class="header">
    <div class="header-side right">
      <div class="header-title"><?= app_escape((string) app_config('app_name')) ?></div>
      <div class="header-subtitle"><?= app_escape((string) app_config('app_subtitle')) ?></div>
    </div>
    <div class="header-center">
      <img src="<?= app_escape(app_logo_path_for_header($company)) ?>" alt="Company 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"><?= app_escape(app_role_label((string) (app_current_user()['role'] ?? 'accountant'))) ?> &bull; <a href="logout.php">Logout</a></div>
    </div>
  </header>

  <div class="date-bar">
    <div class="date-item">Date : <span><?= app_escape(date('Y-m-d')) ?></span></div>
    <div class="date-item">Company : <span><?= app_escape((string) ($company['name'] ?? 'N/A')) ?></span></div>
    <div class="date-author">Prepared by : <?= app_escape((string) (app_current_user()['full_name'] ?? app_current_username())) ?></div>
  </div>

  <?= app_back_button_html('Back') ?>

  <div class="container">
    <section class="panel context-switch-panel screen-only">
      <div class="section-heading">
        <h3>Context</h3>
        <span>Choose company and dashboard template</span>
      </div>
      <form class="form-grid two" method="get">
        <?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: ?>
          <input type="hidden" name="company_id" value="<?= (int) $companyId ?>">
        <?php endif; ?>

        <div class="field">
          <label for="template_id">Report Template</label>
          <select id="template_id" name="template_id" data-auto-submit>
            <option value="">No template</option>
            <?php foreach ($reportTemplates as $template): ?>
              <option value="<?= (int) $template['id'] ?>" <?= (int) $template['id'] === $templateId ? 'selected' : '' ?>>
                <?= app_escape((string) ($template['template_name'] ?? ('Template #' . $template['id']))) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="field">
          <label for="from_date">From Date</label>
          <input id="from_date" name="from_date" type="date" value="<?= app_escape($dashboardFromDate) ?>">
        </div>

        <div class="field">
          <label for="to_date">To Date</label>
          <input id="to_date" name="to_date" type="date" value="<?= app_escape($dashboardToDate) ?>">
        </div>

        <div class="form-actions">
          <button class="btn btn-primary" type="submit">Apply</button>
          <button class="btn btn-secondary" type="button" data-print-page>Print Report</button>
          <a class="btn btn-secondary" href="<?= app_escape($dashboardExportUrl) ?>">Export XLSX</a>
          <a class="btn btn-secondary" href="index.php<?= $companyId ? '?company_id=' . (int) $companyId : '' ?>">Reset</a>
        </div>
      </form>
    </section>

    <main
      id="dashboardReportPrintArea"
      class="print-scope"
      data-print-scope
      data-default-print-target
      data-report-print
      data-print-title="<?= app_escape($dashboardPrintTitle) ?>"
      data-print-logo="<?= app_escape(app_logo_path_for_header($company)) ?>"
    >
    <section class="panel">
      <div class="section-heading">
        <h3>Designed Report Output</h3>
        <span><?= $activeTemplate ? 'Template: ' . app_escape((string) ($activeTemplate['template_name'] ?? '')) : 'No template selected' ?></span>
      </div>
      <?php if (!$activeTemplate): ?>
        <div class="empty-state">No template available yet. Create one from the Report Designer page.</div>
      <?php elseif (!$sections): ?>
        <div class="empty-state">Template exists but has no sections. Edit template configuration in Report Designer.</div>
      <?php else: ?>
        <div class="charts-grid two">
          <?php foreach ($sections as $section): ?>
            <?= render_template_section($section, $companyId, $dashboardFromDate, $dashboardToDate) ?>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </section>

    <section class="table-card">
      <div class="table-header">
        <div>
          <h3><?= app_escape(app_t('Module Activity')) ?></h3>
          <div class="hint"><?= app_escape(app_t('Quick totals per module')) ?></div>
        </div>
      </div>
      <div class="table-wrap">
        <table class="data-table" style="min-width: 860px;">
          <thead>
            <tr>
              <th><?= app_escape(app_t('Module')) ?></th>
              <th><?= app_escape(app_t('Description')) ?></th>
              <th><?= app_escape(app_t('Total Rows')) ?></th>
              <th><?= app_escape(app_t('Open')) ?></th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($visibleModules as $module): ?>
              <?php $slug = (string) ($module['slug'] ?? ''); ?>
              <tr>
                <td><?= app_escape((string) ($module['title'] ?? $slug)) ?></td>
                <td><?= app_escape((string) ($module['description'] ?? '')) ?></td>
                <td><span class="badge badge-soft"><?= app_escape(number_format((int) ($counts[$slug] ?? 0))) ?></span></td>
                <td>
                  <a class="icon-btn" href="module.php?module=<?= app_escape(urlencode($slug)) ?><?= $companyId ? '&company_id=' . (int) $companyId : '' ?>">Open</a>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </section>

    </main>

    <div class="footer">
      <?= app_escape((string) app_config('app_name')) ?> &bull; <?= app_escape(app_t('Full accounting suite with CRUD modules, Excel import, and report designer.')) ?>
    </div>
  </div>

  <button id="floatingPrintBtn" class="floating-print-btn screen-only" type="button">Print</button>
</div>

<script src="assets/app.js"></script>
</body>
</html>


