<?php
$printOptions = is_array($print_options ?? null) ? $print_options : [];
$role = (string)($role ?? 'customer');
$partyLabel = $role === 'supplier' ? 'المورد' : 'العميل';
$partyName = trim((string)($party['name'] ?? $party['party_name'] ?? ''));
$partyCode = trim((string)($party['code'] ?? $party['party_code'] ?? ''));
$partyPhone = trim((string)($party['phone'] ?? $party['party_phone'] ?? ''));
$periodFrom = trim((string)($filters['date_from'] ?? $filters['from'] ?? $from ?? ''));
$periodTo = trim((string)($filters['date_to'] ?? $filters['to'] ?? $to ?? ''));
$openingBalance = (float)($opening ?? 0);
$totalDebit = (float)($totals['debit'] ?? 0);
$totalCredit = (float)($totals['credit'] ?? 0);
$closingBalance = (float)($closing ?? $totals['closing'] ?? $openingBalance);
$rowsCount = count($rows ?? []);
$statementTitle = $role === 'supplier' ? 'كشف حساب مورد' : 'كشف حساب عميل';
$statementTitleEn = $role === 'supplier' ? 'SUPPLIER STATEMENT' : 'CUSTOMER STATEMENT';
$balanceNature = $closingBalance > 0
    ? ($role === 'supplier' ? 'مستحق للمورد' : 'مستحق على العميل')
    : ($closingBalance < 0 ? ($role === 'supplier' ? 'دفع مقدم للمورد' : 'رصيد دائن للعميل') : 'رصيد متزن');
$printNote = trim((string)($printOptions['footer_note'] ?? ''));

$bodySections = print_sections_ordered([
    'party_block' => ['enabled' => true, 'title' => 'بيانات الطرف', 'order' => 10],
    'hero_totals' => ['enabled' => true, 'title' => 'أرصدة رئيسية', 'order' => 20],
    'summary_block' => ['enabled' => true, 'title' => 'ملخص الفترة', 'order' => 30],
    'notes' => ['enabled' => $printNote !== '', 'title' => 'ملاحظات الطباعة', 'order' => 40],
    'items_table' => ['enabled' => true, 'title' => 'حركة الحساب', 'order' => 50],
    'totals' => ['enabled' => true, 'title' => 'إجمالي الكشف', 'order' => 60],
], $printOptions, 'body');

$runningBalance = $openingBalance;
$statementRows = [[
    'date' => $periodFrom !== '' ? $periodFrom : '—',
    'type' => label_def('OPENING_BALANCE', 'statement_doc_type'),
    'ref' => '—',
    'desc' => 'رصيد أول المدة',
    'debit' => null,
    'credit' => null,
    'balance' => $runningBalance,
    'is_opening' => true,
]];
foreach (($rows ?? []) as $row) {
    $debit = (float)($row['debit'] ?? 0);
    $credit = (float)($row['credit'] ?? 0);
    $runningBalance += $debit - $credit;
    $statementRows[] = [
        'date' => substr((string)($row['doc_date'] ?? '—'), 0, 10),
        'type' => label_def((string)($row['doc_type'] ?? '—'), 'statement_doc_type'),
        'ref' => (string)($row['doc_no'] ?? $row['ref_no'] ?? '—'),
        'desc' => trim((string)($row['notes'] ?? '')) !== '' ? (string)$row['notes'] : '—',
        'debit' => $debit,
        'credit' => $credit,
        'balance' => $runningBalance,
        'is_opening' => false,
    ];
}

$firstPageRows = 16;
$nextPageRows = 24;
$chunks = [];
$remaining = $statementRows;
$chunks[] = array_splice($remaining, 0, $firstPageRows);
while ($remaining !== []) {
    $chunks[] = array_splice($remaining, 0, $nextPageRows);
}
$totalPages = max(1, count($chunks));

$renderStatementTable = static function (array $chunk, int $pageNo, int $totalPages, string $sectionTitle): void {
    ?>
    <section class="pi-table-section statement-page<?= $pageNo > 1 ? ' statement-page-follow print-page-break' : '' ?>">
      <?php if ($pageNo > 1): ?>
        <div class="statement-continuation-head keep-together">
          <div>
            <strong><?= e($sectionTitle) ?></strong>
            <span>صفحة <?= e((string)$pageNo) ?> / <?= e((string)$totalPages) ?></span>
          </div>
          <div class="statement-continuation-note">تابع كشف الحساب</div>
        </div>
      <?php endif; ?>
      <div class="pi-section-title"><?= e($sectionTitle) ?> - صفحة <?= e((string)$pageNo) ?> / <?= e((string)$totalPages) ?></div>
      <div class="pi-table-wrap statement-table-wrap">
        <table class="pi-table statement-table">
          <thead>
            <tr>
              <th class="text-center col-date">التاريخ</th>
              <th class="text-center col-type">النوع</th>
              <th class="text-center col-ref">رقم المستند</th>
              <th class="text-center col-desc">البيان</th>
              <th class="text-center col-money">مدين</th>
              <th class="text-center col-money">دائن</th>
              <th class="text-center col-balance">الرصيد</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($chunk as $row): ?>
              <tr<?= !empty($row['is_opening']) ? ' class="statement-opening-row"' : '' ?>>
                <td class="text-center"><?= e((string)$row['date']) ?></td>
                <td class="text-center is-strong"><?= e((string)$row['type']) ?></td>
                <td class="text-center"><?= e((string)$row['ref']) ?></td>
                <td class="statement-desc"><?= e((string)$row['desc']) ?></td>
                <td class="text-center statement-money"><?= $row['debit'] === null ? '—' : e(format_money((float)$row['debit'])) ?></td>
                <td class="text-center statement-money"><?= $row['credit'] === null ? '—' : e(format_money((float)$row['credit'])) ?></td>
                <td class="text-center statement-money is-strong"><?= e(format_money((float)$row['balance'])) ?></td>
              </tr>
            <?php endforeach; ?>
            <?php if ($chunk === []): ?><tr><td colspan="7" class="text-center">لا توجد حركات ضمن الفترة المحددة.</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
    </section>
    <?php
};
?>

<section class="pi-hero statement-title-hero keep-together">
  <div class="pi-title-wrap">
    <h1 class="pi-title"><?= e($statementTitle) ?></h1>
    <div class="pi-title-en"><?= e($statementTitleEn) ?></div>
  </div>
</section>

<?php foreach ($bodySections as $sectionKey => $section): if (empty($section['enabled'])) { continue; } ?>
  <?php if ($sectionKey === 'party_block'): ?>
    <section class="statement-card-section keep-together">
      <div class="pi-party-card statement-party-card statement-wide-card">
        <div class="pi-card-head"><?= e($section['title']) ?></div>
        <div class="statement-party-compact">
          <div class="statement-party-main"><span><?= e($partyLabel) ?></span><strong><?= e($partyName !== '' ? $partyName : '-') ?></strong></div>
          <div><span>الكود</span><strong><?= e($partyCode !== '' ? $partyCode : '-') ?></strong></div>
          <?php if ($partyPhone !== ''): ?><div><span>الهاتف</span><strong><?= e($partyPhone) ?></strong></div><?php endif; ?>
          <div><span>من تاريخ</span><strong><?= e($periodFrom !== '' ? $periodFrom : '—') ?></strong></div>
          <div><span>إلى تاريخ</span><strong><?= e($periodTo !== '' ? $periodTo : '—') ?></strong></div>
          <div><span>عدد الحركات</span><strong><?= e((string)$rowsCount) ?></strong></div>
        </div>
      </div>
    </section>
  <?php elseif ($sectionKey === 'hero_totals'): ?>
    <section class="statement-card-section keep-together">
      <div class="pi-summary-card statement-summary-card statement-wide-card">
        <div class="pi-card-head"><?= e($section['title']) ?></div>
        <div class="pi-summary-stats statement-summary-stats statement-summary-stats--wide">
          <div class="pi-stat-box"><span>رصيد أول المدة</span><strong><?= e(format_money($openingBalance)) ?></strong></div>
          <div class="pi-stat-box"><span>إجمالي مدين</span><strong><?= e(format_money($totalDebit)) ?></strong></div>
          <div class="pi-stat-box"><span>إجمالي دائن</span><strong><?= e(format_money($totalCredit)) ?></strong></div>
          <div class="pi-stat-box is-accent"><span>رصيد آخر المدة</span><strong><?= e(format_money($closingBalance)) ?></strong><em><?= e($balanceNature) ?></em></div>
        </div>
      </div>
    </section>
  <?php elseif ($sectionKey === 'summary_block'): ?>
    <section class="statement-card-section keep-together">
      <div class="pi-total-card statement-period-summary-card">
        <div class="pi-card-head"><?= e($section['title']) ?></div>
        <table class="pi-total-table statement-period-summary-table">
          <tr><td>الفترة</td><td><?= e(($periodFrom !== '' ? $periodFrom : '—') . ' - ' . ($periodTo !== '' ? $periodTo : '—')) ?></td></tr>
          <tr><td>عدد الحركات</td><td><?= e((string)$rowsCount) ?></td></tr>
          <tr><td>طبيعة الرصيد</td><td><?= e($balanceNature) ?></td></tr>
        </table>
      </div>
    </section>
  <?php elseif ($sectionKey === 'notes'): ?>
    <section class="statement-card-section keep-together">
      <div class="pi-terms-card statement-notes-card">
        <div class="pi-card-head"><?= e($section['title']) ?></div>
        <div class="pi-notes-box"><?= e($printNote) ?></div>
      </div>
    </section>
  <?php elseif ($sectionKey === 'items_table'): ?>
    <?php foreach ($chunks as $chunkIndex => $chunk): ?>
      <?php $renderStatementTable($chunk, $chunkIndex + 1, $totalPages, (string)$section['title']); ?>
    <?php endforeach; ?>
  <?php elseif ($sectionKey === 'totals'): ?>
    <section class="pi-bottom-grid keep-together statement-bottom-grid">
      <div></div>
      <div class="pi-total-card statement-total-card">
        <div class="pi-card-head"><?= e($section['title']) ?></div>
        <table class="pi-total-table">
          <tr><td>رصيد أول المدة</td><td><?= e(format_money($openingBalance)) ?></td></tr>
          <tr><td>إجمالي المدين</td><td><?= e(format_money($totalDebit)) ?></td></tr>
          <tr><td>إجمالي الدائن</td><td><?= e(format_money($totalCredit)) ?></td></tr>
          <tr><td>عدد الحركات</td><td><?= e((string)$rowsCount) ?></td></tr>
          <tr class="is-grand"><td>رصيد آخر المدة</td><td><?= e(format_money($closingBalance)) ?></td></tr>
        </table>
      </div>
    </section>
  <?php endif; ?>
<?php endforeach; ?>
