<?php
// ============================================================
//  MediCore — Reporting Engine: run & display a saved report
//  File: reporting/view.php?id={id}
// ============================================================
$page  = 'reporting/view';
$title = 'Reporting Engine';
require_once '../includes/header.php';
require_once '../includes/reporting.php';
ensure_reporting_schema();

$id = (int) ($_GET['id'] ?? 0);

if (!can('reporting_engine')) {
    echo '<div class="content"><div class="al al-w" style="margin-top:20px">
            🔒 You do not have permission to view the Reporting Engine.
          </div></div>';
    require_once '../includes/footer.php';
    exit;
}

$report = $id ? db_row("SELECT * FROM custom_reports WHERE id = ? AND is_active = 1", [$id]) : null;

if (!$report) {
    echo '<div class="content"><div class="al al-w" style="margin-top:20px">
            ⚠ Report not found.
          </div></div>';
    require_once '../includes/footer.php';
    exit;
}

$title = $report['name'];
$def   = json_decode($report['definition'], true) ?: [];
$registry = reporting_registry();
$src   = $registry[$report['data_source']] ?? null;
$hasDate = $src && $src['date_field'];

$from = $_GET['from'] ?? date('Y-m-01');
$to   = $_GET['to']   ?? date('Y-m-d');

$error  = null;
$result = ['columns' => [], 'rows' => []];
try {
    $result = run_custom_report($report['data_source'], $def, $hasDate ? $from : null, $hasDate ? $to : null);
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$isGrouped  = !empty($def['group_by']);
$chartType  = $def['chart_type'] ?? 'none';
$isAdminUser = is_admin();
?>

<div class="page-header">
  <div class="ct" style="font-size:16px"><?= htmlspecialchars($report['icon']) ?> <?= htmlspecialchars($report['name']) ?></div>
  <div style="display:flex;gap:8px;align-items:center">
    <?php if ($isAdminUser): ?>
    <a class="btn btn-sm" href="../settings.php?tab=reporting&edit=<?= $report['id'] ?>">✏ Edit Report</a>
    <?php endif; ?>
    <button class="btn btn-sm" onclick="exportCsv()">📤 Export CSV</button>
  </div>
</div>

<div class="content">

  <?php if ($report['description']): ?>
  <div class="al al-i" style="margin-bottom:12px"><?= htmlspecialchars($report['description']) ?></div>
  <?php endif; ?>

  <?php if ($hasDate): ?>
  <form method="GET" style="display:flex;gap:9px;align-items:center;
        flex-wrap:wrap;margin-bottom:14px;padding:10px 14px;
        background:var(--surface);border:1px solid var(--border);border-radius:var(--r)">
    <input type="hidden" name="id" value="<?= $report['id'] ?>">
    <span style="font-size:12px;font-weight:600;color:var(--text2)">📅 Range:</span>
    <input type="date" name="from" value="<?= $from ?>"
      style="padding:5px 8px;border:1px solid var(--border);border-radius:var(--rsm);font-size:12px;outline:none">
    <span style="color:var(--text3);font-size:11px">to</span>
    <input type="date" name="to" value="<?= $to ?>"
      style="padding:5px 8px;border:1px solid var(--border);border-radius:var(--rsm);font-size:12px;outline:none">
    <button type="submit" class="btn btn-primary btn-sm">Apply</button>
  </form>
  <?php endif; ?>

  <?php if ($error): ?>
  <div class="al al-w" style="color:var(--danger)">⚠ Could not run this report: <?= htmlspecialchars($error) ?></div>
  <?php else: ?>

  <?php if ($chartType !== 'none' && $isGrouped && count($result['rows']) > 0): ?>
  <div class="card" style="margin-bottom:14px">
    <canvas id="reportChart" height="100"></canvas>
  </div>
  <?php endif; ?>

  <div style="display:flex;gap:8px;margin-bottom:10px">
    <input type="text" id="rp-search" placeholder="🔍 Search results…" oninput="filterRows()"
      style="padding:5px 10px;border:1px solid var(--border);border-radius:var(--rsm);
             font-size:12px;outline:none;width:220px">
    <button class="btn btn-sm" onclick="document.getElementById('rp-search').value='';filterRows()">✕ Clear</button>
    <span id="rp-count" style="font-size:11px;color:var(--text3);align-self:center"></span>
  </div>

  <div class="card" style="padding:0">
    <div class="tw" style="overflow-x:auto">
      <table id="rp-table">
        <thead>
          <tr>
            <?php foreach ($result['columns'] as $col): ?>
            <th style="<?= $col['type'] === 'currency' || $col['type'] === 'number' ? 'text-align:right' : '' ?>">
              <?= htmlspecialchars($col['label']) ?>
            </th>
            <?php endforeach; ?>
          </tr>
        </thead>
        <tbody id="rp-body">
          <?php if ($result['rows']): foreach ($result['rows'] as $row): ?>
          <tr class="rp-row" data-name="<?= htmlspecialchars(strtolower(implode(' ', array_map('strval', $row)))) ?>">
            <?php foreach ($result['columns'] as $col):
              $v = $row[$col['key']] ?? '';
              $isNum = in_array($col['type'], ['currency', 'number'], true);
            ?>
            <td class="<?= $isNum ? 'mono' : '' ?>" style="<?= $isNum ? 'text-align:right' : '' ?>">
              <?= $col['type'] === 'currency' ? htmlspecialchars($settings['currency']) . number_format((float)$v, 2)
                  : ($col['type'] === 'number' ? number_format((float)$v) : htmlspecialchars((string)$v)) ?>
            </td>
            <?php endforeach; ?>
          </tr>
          <?php endforeach; else: ?>
          <tr><td colspan="<?= max(1,count($result['columns'])) ?>" class="empty-state">No data for this report</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
    <div id="rp-pager" style="display:flex;align-items:center;padding:8px 12px;border-top:1px solid var(--border)"></div>
  </div>

  <?php endif; ?>

</div><!-- /content -->

<?php if (!$error && $chartType !== 'none' && $isGrouped && count($result['rows']) > 0): ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
(function() {
  const labels = <?= json_encode(array_map(fn($r) => (string)($r[$result['columns'][0]['key']] ?? ''), $result['rows'])) ?>;
  const dataCols = <?= json_encode(array_slice($result['columns'], 1)) ?>;
  const rows = <?= json_encode($result['rows']) ?>;
  const palette = ['rgba(45,58,140,0.75)','rgba(26,158,110,0.75)','rgba(234,88,12,0.75)','rgba(124,58,237,0.75)'];
  const chartType = <?= json_encode($chartType === 'pie' ? 'pie' : ($chartType === 'line' ? 'line' : 'bar')) ?>;

  const datasets = dataCols.map((col, i) => ({
    label: col.label,
    data: rows.map(r => Number(r[col.key]) || 0),
    backgroundColor: chartType === 'pie'
      ? labels.map((_, j) => palette[j % palette.length])
      : palette[i % palette.length],
    borderColor: chartType === 'line' ? palette[i % palette.length] : undefined,
    borderWidth: chartType === 'line' ? 2 : 0,
    fill: chartType === 'line',
    tension: 0.35,
  }));

  new Chart(document.getElementById('reportChart').getContext('2d'), {
    type: chartType,
    data: { labels, datasets },
    options: {
      plugins: { legend: { labels: { font: { size: 10 } } } },
      scales: chartType === 'pie' ? {} : {
        y: { beginAtZero: true, ticks: { font: { size: 10 } } },
        x: { ticks: { font: { size: 10 } } },
      },
    },
  });
})();
</script>
<?php endif; ?>

<script>
let rpPager;

function filterRows() {
  rpPager?.refresh();
}

function exportCsv() {
  const params = new URLSearchParams(window.location.search);
  params.set('action', 'export_csv');
  params.set('id', '<?= $report['id'] ?>');
  window.open('../api/reporting.php?' + params.toString(), '_blank');
}

document.addEventListener('DOMContentLoaded', () => {
  const rows = Array.from(document.querySelectorAll('.rp-row'));
  if (!rows.length) return;
  rpPager = mediPaginate({
    rows,
    predicate: row => {
      const q = document.getElementById('rp-search').value.toLowerCase();
      return !q || row.dataset.name.includes(q);
    },
    pagerEl: document.getElementById('rp-pager'),
    countEl: document.getElementById('rp-count'),
    countLabel: 'row',
    perPage: 25, renumber: false,
  });
});
</script>

<?php require_once '../includes/footer.php'; ?>
