<?php
if (session_status() === PHP_SESSION_NONE) session_start();
if (!ob_get_level()) ob_start();

require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/db_schema_helpers.php';
require_once __DIR__ . '/db_bootstrap.php';

// Graceful auth without hard DB dependency
$logged = !empty($_SESSION['admin_id']) || !empty($_SESSION['admin_user_id']) || !empty($_SESSION['admin_user']);
if (!$logged) {
  header('Location: index.php?login=1');
  exit;
}

$conn = ensure_db(false);
if ($conn instanceof mysqli) {
  $GLOBALS['conn'] = $conn;
  mysqli_report(MYSQLI_REPORT_OFF);
}

/* ---------- helpers ---------- */
if (!function_exists('q1')) {
  function q1(mysqli $conn, string $sql): ?array {
    $r = @$conn->query($sql);
    if ($r && $r->num_rows) return $r->fetch_assoc();
    return null;
  }
}
if (!function_exists('h')) {
  function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
}

/* ---------- session admin ---------- */
$admin_name = $_SESSION['admin_full_name']
  ?? $_SESSION['full_name']
  ?? $_SESSION['admin_username']
  ?? $_SESSION['admin_user']
  ?? 'admin';

$now = date('Y-m-d H:i');

/* ---------- operation id ---------- */
$op_id = (string)($_GET['op'] ?? '');
if ($op_id === '') $op_id = date('YmdHis') . '-' . substr(bin2hex(random_bytes(3)), 0, 6);

/* ---------- company ---------- */
$company = [
  'company_name' => 'اسم الشركة',
  'owner_name'   => 'عماد خميس',
  'phone'        => '',
  'address'      => '',
  'logo_path'    => ''
];

$dbOffline = !($conn instanceof mysqli);
if (!$dbOffline && table_exists($conn, 'company_info')) {
  $r = q1($conn, "SELECT * FROM company_info WHERE id=1 LIMIT 1");
  if ($r) {
    $company['company_name'] = $r['company_name'] ?? $company['company_name'];
    $company['owner_name']   = $r['owner_name'] ?? $company['owner_name'];
    $company['phone']        = $r['phone'] ?? '';
    $company['address']      = $r['address'] ?? '';
    $company['logo_path']    = $r['logo_path'] ?? '';
  }
}

/* ---------- input type ---------- */
$type  = $_GET['type'] ?? 'page'; // page | invoice
$paper = $_GET['paper'] ?? 'A4';
$uaAndroidPrintPreview = ((string)($_GET['ua_android'] ?? '') === '1') || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;

/* ---------- A4 sample invoice preview ---------- */
$sample = [
  'invoice_no' => $_GET['invoice_no'] ?? ('INV-' . rand(1000,9999)),
  'customer'   => $_GET['customer'] ?? 'مشترك تجريبي',
  'date'       => $_GET['date'] ?? date('Y-m-d'),
  'items'      => [
    ['name'=>'اشتراك إنترنت - BASE', 'qty'=>1, 'price'=>120000],
    ['name'=>'باقة إضافية 5GB', 'qty'=>1, 'price'=>25000],
  ],
];

$total = 0;
foreach($sample['items'] as $it){
  $total += ((float)$it['qty'] * (float)$it['price']);
}

/* ---------- layout ---------- */
$dir = 'rtl';
$textAlign = 'right';

$w = 794; // A4 preview width
$padTop = 12; $padRight = 12; $padBottom = 12; $padLeft = 12;
$logoUrl = $company['logo_path'] ?? '';

?>
<!doctype html>
<?php $uaLang = function_exists('current_lang') ? current_lang() : 'ar'; $uaDir = ($uaLang === 'en') ? 'ltr' : ($dir ?? 'rtl'); ?>
<html lang="<?= h($uaLang) ?>" dir="<?= h($uaDir) ?>">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Print Preview</title>
  <?php $ua_print_css_v = @filemtime(__DIR__ . '/assets/css/ua_program_unified.css') ?: 1; ?>
  <link rel="stylesheet" href="assets/css/ua_program_unified.css?v=<?= (int)$ua_print_css_v ?>">
  <?php if($uaAndroidPrintPreview): $uaAndroidPrintCssV=@filemtime(__DIR__.'/assets/css/android_print_preview.css')?:1; ?><link rel="stylesheet" href="assets/css/android_print_preview.css?v=<?= (int)$uaAndroidPrintCssV ?>"><?php endif; ?>
  
</head>
<body class="ua-special-page ua-print-page ua-print-preview-page ua-print-standalone <?= $uaAndroidPrintPreview?'ua-android-print-preview':'' ?>">
  <div class="wrap ua-print-wrap">
    <?php if ($dbOffline): ?>
      <div class="offline-note ua-print-offline-note">تعذر الوصول إلى قاعدة البيانات حالياً، لذلك تم فتح معاينة الطباعة بالوضع التجريبي بدل ظهور خطأ قاتل.</div>
    <?php endif; ?>
    <div class="actions ua-print-toolbar">
      <a class="btn" href="#" onclick="window.print();return false;">طباعة / حفظ PDF</a>
      <a class="btn" href="javascript:history.back()">رجوع</a>
    </div>
    <div class="paper ua-print-sheet ua-preview-sheet">
      <div class="header ua-preview-header">
        <div>
          <div class="name ua-preview-name"><?= h($company['company_name']) ?></div>
          <div class="muted ua-preview-muted">المالك: <?= h($company['owner_name']) ?></div>
          <?php if (!empty($company['phone'])): ?><div class="muted ua-preview-muted">الهاتف: <?= h($company['phone']) ?></div><?php endif; ?>
          <?php if (!empty($company['address'])): ?><div class="muted ua-preview-muted">العنوان: <?= h($company['address']) ?></div><?php endif; ?>
        </div>
        <div class="brand ua-preview-brand">
          <?php if ($logoUrl): ?><img src="<?= h($logoUrl) ?>" alt="logo"><?php endif; ?>
        </div>
      </div>
      <div class="box ua-preview-box">
        <strong>معاينة فاتورة</strong>
        <div class="muted ua-preview-muted">رقم العملية: <?= h($op_id) ?> — التاريخ: <?= h($now) ?> — بواسطة: <?= h($admin_name) ?></div>
      </div>
      <div class="box ua-preview-box">
        <div class="muted ua-preview-muted">رقم الفاتورة</div>
        <div><strong><?= h($sample['invoice_no']) ?></strong></div>
        <div class="muted ua-u-mt-10">العميل: <?= h($sample['customer']) ?> — التاريخ: <?= h($sample['date']) ?></div>
      </div>
      <table class="ua-preview-table">
        <thead><tr><th>البيان</th><th>الكمية</th><th>السعر</th><th>الإجمالي</th></tr></thead>
        <tbody>
          <?php foreach($sample['items'] as $it): ?>
            <tr>
              <td><?= h($it['name']) ?></td>
              <td><?= (float)$it['qty'] ?></td>
              <td><?= number_format((float)$it['price'],2) ?></td>
              <td><?= number_format((float)$it['qty'] * (float)$it['price'],2) ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
        <tfoot>
          <tr><th colspan="3">الإجمالي النهائي</th><th><?= number_format($total,2) ?></th></tr>
        </tfoot>
      </table>
    </div>
  </div>

<?php require_once __DIR__ . '/output_devices_lib.php'; if ($conn instanceof mysqli) ua_output_print_bootstrap($conn, $type === 'invoice' ? 'invoice_a4' : 'general_report', $op_id); ?>
<?php if (function_exists('ua_i18n_json_payload')): ?>
<script>window.UA_I18N = <?= ua_i18n_json_payload() ?: '{}' ?>;</script>
<?php $ua_v_i18n_js = @filemtime(__DIR__ . '/assets/js/ua_i18n.js') ?: time(); ?>
<script src="assets/js/ua_i18n.js?v=<?= (int)$ua_v_i18n_js ?>"></script>
<?php endif; ?>
</body>
</html>
