<?php $title=__('reports.daily', 'Daily Reports'); ob_start(); ?>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4 flex-md-row flex-column">
 
  <h1 class="h3 mt-3">
    <i class="fas fa-chart-bar"></i> <?= __('reports.daily', 'Daily Reports') ?>
  </h1>
   
  <div class="gap-3 d-flex flex-md-row ">
    <button type="button" class="btn btn-secondary mb-2" onclick="window.print()">
      <i class="fas fa-print"></i> <?= __('common.print', 'Print') ?>
    </button>
    <a href="?date=<?= urlencode($date) ?>&export=csv" class="btn btn-success mb-2">
      <i class="fas fa-file-csv"></i> CSV
    </a>
    <a href="?date=<?= urlencode($date) ?>&export=pdf" class="btn btn-danger mb-2">
      <i class="fas fa-file-pdf"></i> PDF
    </a>
    <a href="?date=<?= urlencode($date) ?>&export=excel" class="btn btn-success mb-2">
      <i class="fas fa-file-excel"></i> Excel
    </a>
  </div>
</div>

<!-- Filters Section -->
<form method="GET" class="data-filters">
  <div class="card mb-3 bg-warning-subtle">
    <div class="card-header py-2 d-flex justify-content-between align-items-center">
    
      <span class="small fw-bold">
        <i class="fas fa-filter me-1"></i><?= __('common.filters', 'Filters') ?>
      </span>
      <button class="btn btn-sm btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#filtersWrap">
        <i class="fas fa-chevron-down"></i>
      </button>
    </div>
    <div class="collapse collapsed" id="filtersWrap">
      <div class="card-body py-3">
        <div class="row g-3">
          <div class="col-md-2 col-12">
            <label class="form-label small mb-1">
              <i class="fas fa-calendar me-1"></i><?= __('common.date', 'Date') ?>
            </label>
            <input type="date" name="date" value="<?= htmlspecialchars($date) ?>" class="form-control">
          </div>
          <div class="col-md-7 col-12">
            <label class="form-label small mb-1">
              <i class="fas fa-tags me-1"></i><?= __('reports.flags', 'Report Flags') ?>
            </label>
            <div class="border rounded p-2 bg-light">
              <div class="d-flex flex-wrap gap-2">
                <?php 
                $selectedFlags = $_GET['flag_filter'] ?? [];
                if(!is_array($selectedFlags)) $selectedFlags = [$selectedFlags];
                foreach($allFlags as $f): 
                ?>
                  <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="flag_filter[]" value="<?= htmlspecialchars($f['code']) ?>" id="flag_<?= htmlspecialchars($f['code']) ?>" <?= in_array($f['code'], $selectedFlags)?'checked':'' ?>>
                    <label class="form-check-label small" for="flag_<?= htmlspecialchars($f['code']) ?>">
                      <?= htmlspecialchars($f['label']) ?>
                    </label>
                  </div>
                <?php endforeach; ?>
              </div>
              <small class="text-muted d-block mt-2">
                <i class="fas fa-info-circle me-1"></i><?= __('reports.leave_empty_all', 'Leave empty to show all active reports') ?>
              </small>
            </div>
          </div>
          <div class="col-md-3 col-12">
            <div class="d-flex gap-2">
              <button type="submit" class="btn btn-primary">
                <i class="fas fa-sync me-1"></i><?= __('reports.load', 'Load') ?>
              </button>
              <a href="?date=<?= htmlspecialchars($date) ?>" class="btn btn-outline-secondary">
                <i class="fas fa-times me-1"></i><?= __('common.clear_filters', 'Clear Filters') ?>
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</form>
<?php if(empty($reports)): ?>
  <div class="alert alert-info">
    <i class="fas fa-info-circle me-2"></i><?= __('reports.no_data', 'No report data for selected date.') ?>
  </div>
<?php endif; ?>

<?php foreach($reports as $rep): $flag=$rep['flag']; ?>
  <div class="card mb-4">
    <div class="card-header py-2">
      <span class="small fw-bold">
        <span class="badge bg-secondary me-2"><?= htmlspecialchars($flag['code']) ?></span>
        <?= htmlspecialchars($flag['label']) ?>
        <small class="text-muted">(<?= htmlspecialchars($flag['view_type']) ?>)</small>
      </span>
    </div>
    <div class="card-body pt-0">
    <?php if($rep['view_type']==='category_summary'): ?>
      <?php
        // group rows by category and split across 2 column tables
        $byCat=[]; foreach($rep['rows'] as $r){ $cat=$r['category_name'] ?: 'Uncategorized'; $byCat[$cat][]=$r; }
        if(!empty($byCat)) { ksort($byCat, SORT_NATURAL | SORT_FLAG_CASE); }
        $categories = array_keys($byCat);
        $totalCats = count($categories);
        $half = (int)ceil($totalCats/2);
        $leftCats = array_slice($categories,0,$half);
        $rightCats = array_slice($categories,$half);
      ?>
      <div class="row g-3 mt-1">
        <div class="col-md-6">
          <div class="table-responsive">
            <table class="table table-sm table-bordered table-hover align-middle mb-0">
              <thead class="table-light"><tr><th style="width:55%"><?= __("common.name", "Name") ?></th><th style="width:10%" class="text-end">Qty</th><th style="width:10%">Unit</th></tr></thead>
              <tbody>
              <?php if(!$leftCats): ?>
                <tr><td colspan="3" class="text-muted text-center">No data</td></tr>
              <?php else: ?>
                <?php foreach($leftCats as $catName): $rows=$byCat[$catName]; ?>
                  <tr class="table-secondary"><td colspan="3" class="fw-bold"><?= htmlspecialchars($catName) ?></td></tr>
                  <?php foreach($rows as $row): ?>
                  <tr>
                    <td><?= htmlspecialchars($row['name']) ?></td>
                    <td class="text-end"><?= $row['qty']+0 ?></td>
                    <td><?= htmlspecialchars($row['production_unit'] ?? '') ?></td>
                  </tr>
                  <?php endforeach; ?>
                <?php endforeach; ?>
              <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
        <div class="col-md-6">
          <div class="table-responsive">
            <table class="table table-sm table-bordered table-hover align-middle mb-0">
              <thead class="table-light"><tr><th style="width:55%"><?= __("common.name", "Name") ?></th><th style="width:10%" class="text-end">Qty</th><th style="width:10%">Unit</th></tr></thead>
              <tbody>
              <?php if(!$rightCats): ?>
                <tr><td colspan="3" class="text-muted text-center">&nbsp;</td></tr>
              <?php else: ?>
                <?php foreach($rightCats as $catName): $rows=$byCat[$catName]; ?>
                  <tr class="table-secondary"><td colspan="3" class="fw-bold"><?= htmlspecialchars($catName) ?></td></tr>
                  <?php foreach($rows as $row): ?>
                  <tr>
                    <td><?= htmlspecialchars($row['name']) ?></td>
                    <td class="text-end"><?= $row['qty']+0 ?></td>
                    <td><?= htmlspecialchars($row['production_unit'] ?? '') ?></td>
                  </tr>
                  <?php endforeach; ?>
                <?php endforeach; ?>
              <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    <?php elseif($rep['view_type']==='category_with_customers'): ?>
      <?php $customers=$rep['customers']; $rows=$rep['rows'];
        // Build column headers with short names (first 3 letters unless contains multibyte) - here simple substr
        $custShort=[]; foreach($customers as $c){ $custShort[$c['id']] = mb_substr($c['name'],0,3); }
        // group by category
        $byCat=[]; foreach($rows as $row){ $cat=$row['category_name'] ?: 'Uncategorized'; $byCat[$cat][]=$row; }
      ?>
      <div class="table-responsive mt-1">
        <table class="table table-sm table-bordered table-hover align-middle mb-0">
          <thead class="table-light">
            <tr>
              <th style="min-width:240px"><?= __("common.name", "Name") ?></th>
              <?php foreach($customers as $c): ?>
                <th class="text-end" title="<?= htmlspecialchars($c['name']) ?>"><?= htmlspecialchars($custShort[$c['id']]) ?></th>
              <?php endforeach; ?>
              <th class="text-end"><?= __('common.total', 'Total') ?></th>
              <th class="text-end"><?= __('common.unit', 'Unit') ?></th>
            </tr>
          </thead>
          <tbody>
            <?php foreach($byCat as $catName=>$prows): ?>
              <tr class="table-secondary"><td colspan="<?= count($customers)+2 ?>" class="fw-bold"><?= htmlspecialchars($catName) ?></td></tr>
              <?php foreach($prows as $prow): ?>
                <tr>
                  <td><?= htmlspecialchars($prow['name']) ?></td>
                  <?php foreach($customers as $c): $val=$prow['customers'][$c['id']] ?? ''; ?>
                    <td class="text-end"><?= $val!==''? ($val+0):'' ?></td>
                  <?php endforeach; ?>
                  <td class="text-end fw-bold"><?= $prow['total']+0 ?></td>
                  <td class="text-end"><?= htmlspecialchars($prow['production_unit'] ?? '') ?></td>
                </tr>
              <?php endforeach; ?>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
    </div>
  </div>
<?php endforeach; ?>

<?php if(!empty($additionalProducts)): ?>
  <div class="card mb-4">
    <div class="card-header py-2">
      <span class="small fw-bold text-success">
        <i class="fas fa-plus-circle me-1"></i><?= __('reports.additional_products', 'Additional Products (Ordered)') ?>
      </span>
    </div>
    <div class="card-body pt-0">
      <div class="table-responsive mt-1">
        <table class="table table-sm table-bordered table-hover align-middle mb-0">
        <thead class="table-light"><tr><th style="min-width:220px"><?= __('common.product', 'Product') ?></th><th><?= __('reports.customers_qty', 'Customers (qty)') ?></th><th class="text-end"><?= __('common.total', 'Total') ?></th></tr></thead>
        <tbody>
          <?php foreach($additionalProducts as $ap): ?>
            <tr>
              <td><?= htmlspecialchars($ap['product_name']) ?></td>
              <td>
                <?php $list=[]; foreach($ap['customers'] as $cid=>$cd){ $list[] = htmlspecialchars($cd['name']).' <span class=\'badge bg-secondary\'>'.($cd['qty']+0).'</span>'; } echo implode(' ', $list); ?>
              </td>
              <td class="text-end fw-bold"><?= $ap['total']+0 ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
      </div>
    </div>
  </div>
<?php endif; ?>

<?php if(!empty($blockedProducts)): ?>
  <div class="card mb-4">
    <div class="card-header py-2">
      <span class="small fw-bold text-danger">
        <i class="fas fa-ban me-1"></i><?= __('reports.blocked_products', 'Blocked Products') ?>
      </span>
    </div>
    <div class="card-body pt-0">
      <div class="table-responsive mt-1">
        <table class="table table-sm table-bordered table-hover align-middle mb-0">
        <thead class="table-dark"><tr><th style="min-width:220px"><?= __('common.product', 'Product') ?></th><th><?= __('reports.customers_qty', 'Customers (qty)') ?></th><th class="text-end"><?= __('common.total', 'Total') ?></th></tr></thead>
        <tbody>
          <?php foreach($blockedProducts as $bp): ?>
            <tr class="table-warning">
              <td><?= htmlspecialchars($bp['product_name']) ?></td>
              <td>
                <?php $list=[]; foreach($bp['customers'] as $cid=>$cd){ $list[] = htmlspecialchars($cd['name']).' <span class=\'badge bg-danger\'>'.($cd['qty']+0).'</span>'; } echo implode(' ', $list); ?>
              </td>
              <td class="text-end fw-bold"><?= $bp['total']+0 ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
      </div>
    </div>
  </div>
<?php endif; ?>

<?php $content=ob_get_clean(); require __DIR__.'/../layout.php'; ?>


