<?php
$page_title = 'عرض الفواتير';
$UA_FORCE_DESIGN_V2 = true;
$uaAndroidInvoices = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidInvoices) $UA_PAGE_CSS = ['assets/css/android_invoices.css'];
require_once __DIR__ . '/header.php';
require_once __DIR__ . '/sidebar.php';
require_once __DIR__ . '/db_schema_helpers.php';
require_once __DIR__ . '/finance_payment_lib.php';

$finance_active = 'invoices';
$finance_group = 'billing';
$conn = $GLOBALS['conn'] ?? ($conn ?? null);
if (!($conn instanceof mysqli)) {
  echo "<div class='content-wrapper'><section class='content p-3'><div class='alert alert-danger'>خطأ: اتصال قاعدة البيانات غير جاهز.</div></section></div>";
  require_once __DIR__ . '/footer.php';
  exit;
}

mysqli_report(MYSQLI_REPORT_OFF);

if (!function_exists('h')) {
  function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
}

$hasInvoices = table_exists($conn, 'invoices');

$flash_success = $_SESSION['flash_success'] ?? '';
$flash_warning = $_SESSION['flash_warning'] ?? '';
unset($_SESSION['flash_success'], $_SESSION['flash_warning']);

$rows = [];
if ($hasInvoices) {
  $hasSubs = table_exists($conn,'subscribers');
  $sql = "SELECT i.*" . ($hasSubs ? ", s.full_name AS subscriber_name" : "") . " FROM invoices i "
       . ($hasSubs ? "LEFT JOIN subscribers s ON i.subscriber_id = s.id " : "")
       . ($hasSubs ? "WHERE ".(function_exists('subs_active_where_sql') ? subs_active_where_sql($conn,'s') : 'COALESCE(s.is_deleted,0)=0') : "")
       . " ORDER BY i.id DESC LIMIT 200";
  $res = @$conn->query($sql);
  if ($res) while ($invoiceRow = $res->fetch_assoc()) $rows[] = $invoiceRow;
}

if ($uaAndroidInvoices) {
  require __DIR__ . '/android_invoices.php';
  finance_render_auto_print($conn, (int)($_GET['auto_print_invoice'] ?? 0));
  require_once __DIR__ . '/footer.php';
  return;
}

?>
<div class="content-wrapper ua-extracted-page">
  <section class="content-header">
    <div class="container-fluid d-flex justify-content-between align-items-center">
      <h1 class="mb-0">الفواتير</h1>
      <div>
        <a href="invoices_generate_month.php" class="btn btn-primary"><i class="fa fa-calendar"></i> إعداد دورة الفوترة</a>
        <a href="invoices_add.php" class="btn btn-success"><i class="fa fa-plus"></i> إنشاء فاتورة</a>
      </div>
    </div>
  </section>

  <section class="content">
    <div class="container-fluid">

      <?php include __DIR__ . '/finance_tabs.php'; ?>

      <?php if(!empty($flash_success)){ ?><div class="alert alert-success"><?= h($flash_success) ?></div><?php } ?>
      <?php if(!empty($flash_warning)){ ?><div class="alert alert-warning"><?= h($flash_warning) ?></div><?php } ?>


      <?php if(!$hasInvoices){ ?>
        <div class="alert alert-danger">
          جدول <b>invoices</b> غير موجود في قاعدة البيانات. أنشئه من phpMyAdmin عبر SQL التالي:
          <pre class="ua-u-pre-wrap ua-u-mt-10" dir="ltr"><?php echo h(
"CREATE TABLE IF NOT EXISTS `invoices` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `subscriber_id` INT NULL,
  `amount` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
  `status` VARCHAR(20) NOT NULL DEFAULT 'غير مدفوع',
  `cycle_month` VARCHAR(7) NULL,
  `invoice_type` VARCHAR(30) NOT NULL DEFAULT 'BASE',
  `notes` TEXT NULL,
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `paid_at` DATETIME NULL,
  PRIMARY KEY (`id`),
  KEY `idx_subscriber` (`subscriber_id`),
  KEY `idx_status` (`status`),
  KEY `idx_cycle` (`cycle_month`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"
); ?></pre>
        </div>
      <?php } else { ?>

        <?php
        // محاولة جلب الفواتير + اسم المشترك إن وجد subscribers
        $hasSubs = table_exists($conn,'subscribers');
        $sql = "
          SELECT i.*" . ($hasSubs ? ", s.full_name AS subscriber_name" : "") . "
          FROM invoices i
          " . ($hasSubs ? "LEFT JOIN subscribers s ON i.subscriber_id = s.id" : "") . "
          " . ($hasSubs ? "WHERE ".(function_exists('subs_active_where_sql') ? subs_active_where_sql($conn,'s') : 'COALESCE(s.is_deleted,0)=0') : "") . "
          ORDER BY i.id DESC
          LIMIT 200
        ";
        $rows = [];
        $res = @$conn->query($sql);
        if($res){
          while($r = $res->fetch_assoc()) $rows[] = $r;
        }
        ?>

        <div class="card">
          <div class="card-body table-responsive">
            <table class="table table-bordered table-striped">
              <thead>
                <tr>
                  <th>#</th>
                  <th>المشترك</th>
                  <th>الشهر</th>
                  <th>النوع</th>
                  <th>المبلغ</th>
                  <th>المدفوع</th>
                  <th>المتبقي</th>
                  <th>الحالة</th>
                  <th>التاريخ</th>
                  <th>إجراء</th>
                </tr>
              </thead>
              <tbody>
                <?php if(!$rows){ ?>
                  <tr><td colspan="10" class="text-center">لا توجد فواتير</td></tr>
                <?php } else { foreach($rows as $r){ ?>
                  <tr>
                    <td><?= (int)$r['id'] ?></td>
                    <td><?= h($r['subscriber_name'] ?? '-') ?></td>
                    <td><?= h($r['cycle_month'] ?? '-') ?></td>
                    <td>
                      <?php if (strtoupper((string)($r['cycle_type'] ?? 'AUTOMATIC')) === 'EXCEPTIONAL'): ?>
                        <span class="badge badge-warning"><i class="fa fa-bolt"></i> استثنائية</span>
                      <?php else: ?>
                        <?= h($r['invoice_type'] ?? 'BASE') ?>
                      <?php endif; ?>
                    </td>
                    <td><?= number_format((float)($r['amount'] ?? 0), 2) ?></td>
                    <td><?= number_format((float)($r['paid_amount'] ?? 0), 2) ?></td>
                    <td><?= number_format((float)($r['remaining_amount'] ?? ($r['amount'] ?? 0)), 2) ?></td>
                    <td><?= h($r['status'] ?? '-') ?></td>
                    <td><?= h($r['created_at'] ?? '-') ?></td>
                    <td>
                      <?php $id = (int)$r['id']; ?>
                      <button type="button" class="btn btn-sm btn-primary ua-print-btn" data-id="<?= $id ?>">
                        <i class="fa fa-print"></i> طباعة
                      </button>

                      <?php
                        $st = trim((string)($r['status'] ?? ''));
                        $ps = strtolower(trim((string)($r['payment_status'] ?? '')));
                        $isPaid = in_array($ps, ['paid','settled'], true) || $st === "\xD9\x85\xD8\xAF\xD9\x81\xD9\x88\xD8\xB9" || strtolower($st) === 'paid';
                        $paymentDue = finance_invoice_payment_due($r);
                      ?>
                      <?php if($isPaid){ ?>
                        <span class="badge badge-success ml-1">مدفوعة</span>
                      <?php } elseif($paymentDue) { ?>
                        <a class="btn btn-sm btn-success ml-1" href="pay_invoice.php?id=<?= $id ?>">تسديد</a>
                      <?php } else { ?>
                        <span class="badge badge-secondary ml-1">يتفعل يوم الاستحقاق</span>
                      <?php } ?>
                    </td>
                  </tr>
                <?php }} ?>
              </tbody>
            </table>
          </div>
        </div>

      <?php } ?>

    </div>
  </section>
</div>

<?php finance_render_auto_print($conn, (int)($_GET['auto_print_invoice'] ?? 0)); ?>


<!-- ===== Print Picker Modal (no Bootstrap dependency) ===== -->
<div id="uaPrintOverlay" class="ua-print-overlay ua-u-hidden"></div>
<div id="uaPrintModal" class="ua-print-modal ua-u-hidden">
  <div class="ua-print-modal-head">
    <div class="ua-u-fw-700">اختر نوع الورق للطباعة</div>
    <button type="button" id="uaPrintClose" class="btn btn-sm btn-light">×</button>
  </div>
  <div class="ua-print-modal-body">
    <div class="ua-print-modal-note">سيتم فتح صفحة الطباعة في نافذة جديدة.</div>
    <div class="ua-u-flex-wrap-gap10">
      <button type="button" class="btn btn-outline-primary ua-paper" data-paper="A4">A4</button>
      <button type="button" class="btn btn-outline-primary ua-paper" data-paper="80mm">80mm</button>
      <button type="button" class="btn btn-outline-primary ua-paper" data-paper="58mm">58mm</button>
    </div>
    <div class="ua-print-modal-footnote">سيتم تذكّر آخر اختيار تلقائيًا.</div>
  </div>
</div>

<script>
(function(){
  var lastPaper = localStorage.getItem('ua_print_paper') || '80mm';
  var currentId = null;

  function qs(sel){ return document.querySelector(sel); }
  function qsa(sel){ return Array.prototype.slice.call(document.querySelectorAll(sel)); }

  function openModal(id){
    currentId = id;
    // highlight last choice
    qsa('.ua-paper').forEach(function(b){
      var p = b.getAttribute('data-paper');
      if(p === lastPaper){ b.classList.add('active'); }
      else { b.classList.remove('active'); }
    });
    qs('#uaPrintOverlay').style.display = 'block';
    qs('#uaPrintModal').style.display = 'block';
  }

  function closeModal(){
    qs('#uaPrintOverlay').style.display = 'none';
    qs('#uaPrintModal').style.display = 'none';
    currentId = null;
  }

  document.addEventListener('click', function(e){
    var btn = e.target.closest ? e.target.closest('.ua-print-btn') : null;
    if(btn){
      e.preventDefault();
      var id = btn.getAttribute('data-id');
      if(!id) return;
      openModal(id);
      return;
    }
    if(e.target && (e.target.id === 'uaPrintOverlay' || e.target.id === 'uaPrintClose')){
      closeModal();
      return;
    }
    var paperBtn = e.target.closest ? e.target.closest('.ua-paper') : null;
    if(paperBtn){
      var paper = paperBtn.getAttribute('data-paper') || '80mm';
      lastPaper = paper;
      try{ localStorage.setItem('ua_print_paper', paper); }catch(_){}
      if(!currentId){ closeModal(); return; }
      // Open print page in new tab, auto print
      var url = 'print_invoice.php?id=' + encodeURIComponent(currentId) + '&paper=' + encodeURIComponent(paper) + '&auto=1';
      window.open(url, '_blank', 'noopener');
      closeModal();
      return;
    }
  });

  document.addEventListener('keydown', function(e){
    if(e.key === 'Escape') closeModal();
  });
})();
</script>
<!-- ===== /Print Picker Modal ===== -->

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