<?php
$this->load->view('partials/report_start', $this->data);
$report = isset($report) ? $report : array();
$cardnumber = isset($cardnumber) ? $cardnumber : '';
$can_export = !empty($printNumber) && !empty($preview_html);

// Prefer Designation; never show Course
$table_columns = array();
if (!empty($report) && is_array($report[0])) {
    foreach ($report[0] as $key => $unused) {
        if (strcasecmp((string) $key, 'Course') === 0) {
            continue;
        }
        $label = ($key === 'Designation') ? 'Designation' : $key;
        $table_columns[$label] = $key;
    }
    if (!isset($table_columns['Designation']) && !isset($table_columns['designation'])) {
        // Place Designation after Name when possible
        $ordered = array();
        foreach ($table_columns as $label => $key) {
            $ordered[$label] = $key;
            if ($key === 'Name' || $key === 'name') {
                $ordered['Designation'] = 'Designation';
            }
        }
        if (!isset($ordered['Designation'])) {
            $ordered['Designation'] = 'Designation';
        }
        $table_columns = $ordered;
    }
}
?>
<form method="post">
  <div class="row filter-row align-items-end mb-3">
    <div class="col-md-4">
      <div class="form-group mb-0">
        <label>Card Number</label>
        <input type="text" class="form-control" name="cardnumber" value="<?php echo htmlspecialchars($cardnumber); ?>" required placeholder="Enter card number">
      </div>
    </div>
    <div class="col-md-5">
      <p class="mb-0 text-muted small mt-4">Check dues. When eligible, preview the No Dues Certificate, then export.</p>
    </div>
    <div class="col-md-3">
      <?php $this->load->view('partials/report_actions'); ?>
    </div>
  </div>
<?php if (!empty($alert)) { ?>
  <div class="alert alert-warning"><?php echo htmlspecialchars($alert); ?></div>
<?php } ?>
<?php if (!empty($searched)) { ?>
  <div class="report-results-toolbar">
    <p class="report-summary mb-0">
      <?php if (!empty($message)) { ?>
        Status: <strong><?php echo htmlspecialchars($message); ?></strong>
        <?php if (!empty($printNumber)) { ?> — Ref No: <strong><?php echo htmlspecialchars($printNumber); ?></strong><?php } ?>
      <?php } else { ?>
        <strong><?php echo count($report); ?></strong> result(s)
      <?php } ?>
    </p>
    <?php if ($can_export) {
        $this->load->view('partials/report_exports');
    } ?>
  </div>
  <?php if ($can_export) {
      $this->load->view('partials/report_preview');
  } elseif (!empty($report) && empty($printNumber)) {
      $this->load->view('partials/report_datatable', array(
          'columns' => $table_columns,
          'rows' => $report,
          'table_id' => 'dueClearanceTable',
      ));
  } ?>
<?php } ?>
</form>
<?php $this->load->view('partials/report_end'); ?>
