<?php
// admin/settings_print.php

$page_title = 'إعدادات الطباعة';

if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/db_schema_helpers.php';
require_once __DIR__ . '/db_bootstrap.php';
$conn = ensure_db(true);
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/lang.php';

require_login();
if(function_exists('require_perm')) require_perm('can_settings');

$UA_FORCE_DESIGN_V2 = true;
$uaAndroidSettingsPrint = ((string)($_GET['ua_android'] ?? '') === '1') || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
$UA_PAGE_CSS = ['assets/css/settings_print.css'];
if ($uaAndroidSettingsPrint) $UA_PAGE_CSS[] = 'assets/css/android_settings_print.css';
require_once __DIR__ . '/header.php';
if (!defined('UA_EMBED') || !UA_EMBED) require_once __DIR__ . '/sidebar.php';

// ✅ صلاحيات: يدعم require_permission أو require_perm أو لا شيء
if (function_exists('require_permission')) {
  @require_permission('can_manage_print');
} elseif (function_exists('require_perm')) {
  @require_perm('can_manage_print');
}

$conn = $GLOBALS['conn'] ?? ($conn ?? null);
if (!($conn instanceof mysqli)) {
  die('خطأ: اتصال قاعدة البيانات غير جاهز');
}
mysqli_report(MYSQLI_REPORT_OFF);

/* ---------- Helpers (guarded) ---------- */

/* ---------- DB: create + migrate ---------- */
if (!table_exists($conn, 'print_settings')) {
  @$conn->query("
    CREATE TABLE print_settings (
      id INT AUTO_INCREMENT PRIMARY KEY,

      -- Agent host (ويندوز/شبكة) لكل طابعة
      page_agent_host VARCHAR(120) NULL,
      invoice_agent_host VARCHAR(120) NULL,

      -- الطابعة الرئيسية (صفحات/تقارير)
      page_printer VARCHAR(200) NULL,
      page_paper VARCHAR(20) NOT NULL DEFAULT 'A4',
      page_copies INT NOT NULL DEFAULT 1,
      page_color_mode VARCHAR(20) NOT NULL DEFAULT 'BW',      -- BW / COLOR
      page_align_mode VARCHAR(20) NOT NULL DEFAULT 'RTL',     -- RTL / LTR / CENTER
      page_margin_top INT NOT NULL DEFAULT 5,
      page_margin_right INT NOT NULL DEFAULT 5,
      page_margin_bottom INT NOT NULL DEFAULT 5,
      page_margin_left INT NOT NULL DEFAULT 5,

      -- طابعة الفواتير (حراري)
      invoice_printer VARCHAR(200) NULL,
      invoice_paper VARCHAR(20) NOT NULL DEFAULT '80mm',      -- 80mm / 58mm
      invoice_copies INT NOT NULL DEFAULT 1,
      invoice_color_mode VARCHAR(20) NOT NULL DEFAULT 'BW',
      invoice_align_mode VARCHAR(20) NOT NULL DEFAULT 'RTL',
      invoice_margin_top INT NOT NULL DEFAULT 5,
      invoice_margin_right INT NOT NULL DEFAULT 5,
      invoice_margin_bottom INT NOT NULL DEFAULT 5,
      invoice_margin_left INT NOT NULL DEFAULT 5,
      invoice_show_logo TINYINT(1) NOT NULL DEFAULT 1,
      invoice_show_qr TINYINT(1) NOT NULL DEFAULT 1,
      invoice_footer_note VARCHAR(255) NULL,
      invoice_qr_template TEXT NULL,

      updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  ");
} else {
  $adds = [
    "page_agent_host VARCHAR(120) NULL",
    "invoice_agent_host VARCHAR(120) NULL",

    "page_printer VARCHAR(200) NULL",
    "page_paper VARCHAR(20) NOT NULL DEFAULT 'A4'",
    "page_copies INT NOT NULL DEFAULT 1",
    "page_color_mode VARCHAR(20) NOT NULL DEFAULT 'BW'",
    "page_align_mode VARCHAR(20) NOT NULL DEFAULT 'RTL'",
    "page_margin_top INT NOT NULL DEFAULT 5",
    "page_margin_right INT NOT NULL DEFAULT 5",
    "page_margin_bottom INT NOT NULL DEFAULT 5",
    "page_margin_left INT NOT NULL DEFAULT 5",

    "invoice_printer VARCHAR(200) NULL",
    "invoice_paper VARCHAR(20) NOT NULL DEFAULT '80mm'",
    "invoice_copies INT NOT NULL DEFAULT 1",
    "invoice_color_mode VARCHAR(20) NOT NULL DEFAULT 'BW'",
    "invoice_align_mode VARCHAR(20) NOT NULL DEFAULT 'RTL'",
    "invoice_margin_top INT NOT NULL DEFAULT 5",
    "invoice_margin_right INT NOT NULL DEFAULT 5",
    "invoice_margin_bottom INT NOT NULL DEFAULT 5",
    "invoice_margin_left INT NOT NULL DEFAULT 5",
    "invoice_show_logo TINYINT(1) NOT NULL DEFAULT 1",
    "invoice_show_qr TINYINT(1) NOT NULL DEFAULT 1",
    "invoice_footer_note VARCHAR(255) NULL",
    "invoice_qr_template TEXT NULL"
  ];
  foreach ($adds as $def) {
    $col = trim(explode(' ', $def, 2)[0]);
    if (!col_exists($conn, 'print_settings', $col)) {
      @ $conn->query("ALTER TABLE print_settings ADD COLUMN $def");
    }
  }
}

// تأمين صف افتراضي
$r = @$conn->query('SELECT id FROM print_settings WHERE id=1');
if(!$r || !$r->num_rows){
  @ $conn->query('INSERT INTO print_settings (id) VALUES (1)');
}

// ✅ إعدادات افتراضية لكل جهاز (Agent Host)
if (!table_exists($conn, 'print_device_defaults')) {
  @ $conn->query("
    CREATE TABLE print_device_defaults (
      id INT AUTO_INCREMENT PRIMARY KEY,
      host VARCHAR(120) NOT NULL,
      kind VARCHAR(20) NOT NULL,
      settings_json LONGTEXT NOT NULL,
      updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      UNIQUE KEY host_kind (host, kind)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  " );
}

if (!function_exists('get_device_defaults')) {
  function get_device_defaults(mysqli $conn, string $host, string $kind): array {
    $h = $conn->real_escape_string(trim($host));
    $k = $conn->real_escape_string(trim($kind));
    if ($h === '' || $k === '') return [];
    $q = @ $conn->query("SELECT settings_json FROM print_device_defaults WHERE host='$h' AND kind='$k' LIMIT 1");
    if ($q && $q->num_rows) {
      $row = $q->fetch_assoc();
      $js = $row['settings_json'] ?? '';
      $arr = json_decode($js, true);
      return is_array($arr) ? $arr : [];
    }
    return [];
  }
}

if (!function_exists('save_device_defaults')) {
  function save_device_defaults(mysqli $conn, string $host, string $kind, array $settings): bool {
    $host = trim($host);
    if ($host === '') return false;
    if (!in_array($kind, ['page','invoice'], true)) return false;
    $h2 = $conn->real_escape_string($host);
    $k2 = $conn->real_escape_string($kind);
    $json = $conn->real_escape_string(json_encode($settings, JSON_UNESCAPED_UNICODE));
    return (bool)@ $conn->query("
      INSERT INTO print_device_defaults(host,kind,settings_json)
      VALUES('$h2','$k2','$json')
      ON DUPLICATE KEY UPDATE settings_json=VALUES(settings_json)
    ");
  }
}

$msg = ''; $err = '';

/* ---------- Save ---------- */
if (isset($_POST['save'])) {
  // Agent hosts
  $page_agent_host = trim($_POST['page_agent_host'] ?? '127.0.0.1');
  $invoice_agent_host = trim($_POST['invoice_agent_host'] ?? '127.0.0.1');

  // الرئيسية
  $page_printer = trim($_POST['page_printer'] ?? '');
  $page_paper = $_POST['page_paper'] ?? 'A4';
  if (!in_array($page_paper, ['A4','A5','Letter'], true)) $page_paper = 'A4';

  $page_copies = (int)($_POST['page_copies'] ?? 1);
  if ($page_copies < 1) $page_copies = 1;

  $page_color_mode = ($_POST['page_color_mode'] ?? 'BW') === 'COLOR' ? 'COLOR' : 'BW';
  $page_align_mode = $_POST['page_align_mode'] ?? 'RTL';
  if (!in_array($page_align_mode, ['RTL','LTR','CENTER'], true)) $page_align_mode = 'RTL';

  $page_mt = max(0, (int)($_POST['page_margin_top'] ?? 5));
  $page_mr = max(0, (int)($_POST['page_margin_right'] ?? 5));
  $page_mb = max(0, (int)($_POST['page_margin_bottom'] ?? 5));
  $page_ml = max(0, (int)($_POST['page_margin_left'] ?? 5));

  // الفواتير
  $invoice_printer = trim($_POST['invoice_printer'] ?? '');
  $invoice_paper = $_POST['invoice_paper'] ?? '80mm';
  if (!in_array($invoice_paper, ['80mm','58mm'], true)) $invoice_paper = '80mm';

  $invoice_copies = (int)($_POST['invoice_copies'] ?? 1);
  if ($invoice_copies < 1) $invoice_copies = 1;

  $invoice_color_mode = ($_POST['invoice_color_mode'] ?? 'BW') === 'COLOR' ? 'COLOR' : 'BW';
  $invoice_align_mode = $_POST['invoice_align_mode'] ?? 'RTL';
  if (!in_array($invoice_align_mode, ['RTL','LTR','CENTER'], true)) $invoice_align_mode = 'RTL';

  $invoice_mt = max(0, (int)($_POST['invoice_margin_top'] ?? 5));
  $invoice_mr = max(0, (int)($_POST['invoice_margin_right'] ?? 5));
  $invoice_mb = max(0, (int)($_POST['invoice_margin_bottom'] ?? 5));
  $invoice_ml = max(0, (int)($_POST['invoice_margin_left'] ?? 5));

  $invoice_show_logo = isset($_POST['invoice_show_logo']) ? 1 : 0;
  $invoice_show_qr   = isset($_POST['invoice_show_qr']) ? 1 : 0;
  $invoice_footer_note = trim($_POST['invoice_footer_note'] ?? '');
  $invoice_qr_template = trim($_POST['invoice_qr_template'] ?? '');
  if (strlen($invoice_qr_template) > 2000) $invoice_qr_template = substr($invoice_qr_template, 0, 2000);

  $stmt = $conn->prepare("
    UPDATE print_settings
    SET
      page_agent_host=?, invoice_agent_host=?,

      page_printer=?, page_paper=?, page_copies=?, page_color_mode=?, page_align_mode=?,
      page_margin_top=?, page_margin_right=?, page_margin_bottom=?, page_margin_left=?,

      invoice_printer=?, invoice_paper=?, invoice_copies=?, invoice_color_mode=?, invoice_align_mode=?,
      invoice_margin_top=?, invoice_margin_right=?, invoice_margin_bottom=?, invoice_margin_left=?,
      invoice_show_logo=?, invoice_show_qr=?, invoice_footer_note=?, invoice_qr_template=?
    WHERE id=1
  ");

  if (!$stmt) {
    $err = 'DB Error: ' . $conn->error;
  } else {
    $types = 'ssssissiiiississiiiiiiss';
    $stmt->bind_param(
      $types,
      $page_agent_host, $invoice_agent_host,

      $page_printer, $page_paper, $page_copies, $page_color_mode, $page_align_mode,
      $page_mt, $page_mr, $page_mb, $page_ml,

      $invoice_printer, $invoice_paper, $invoice_copies, $invoice_color_mode, $invoice_align_mode,
      $invoice_mt, $invoice_mr, $invoice_mb, $invoice_ml,
      $invoice_show_logo, $invoice_show_qr, $invoice_footer_note, $invoice_qr_template
    );

    if ($stmt->execute()) {
      $msg = t('تم حفظ الإعدادات بنجاح ✅');
    } else {
      $err = 'DB Error: ' . $conn->error;
    }
  }
}



// ✅ حفظ كإعدادات افتراضية لهذا الجهاز
if (isset($_POST['save_device_page']) || isset($_POST['save_device_invoice'])) {
  // إعادة استخدام نفس القيم المُنقّحة من POST (إذا لم تكن موجودة سيتم أخذها من DB)
  $kind = isset($_POST['save_device_page']) ? 'page' : 'invoice';
  $host = trim($kind==='page' ? ($page_agent_host ?? ($_POST['page_agent_host'] ?? '')) : ($invoice_agent_host ?? ($_POST['invoice_agent_host'] ?? '')));

  // لو لم يمرّ عبر كتلة save (مثلاً ضغط زر حفظ افتراضي فقط) نجهّز المتغيرات من POST الآن
  if (!isset($page_agent_host)) {
    $page_agent_host = trim($_POST['page_agent_host'] ?? '127.0.0.1');
    $invoice_agent_host = trim($_POST['invoice_agent_host'] ?? '127.0.0.1');
    $page_printer = trim($_POST['page_printer'] ?? '');
    $page_paper = $_POST['page_paper'] ?? 'A4';
    if (!in_array($page_paper, ['A4','A5','Letter'], true)) $page_paper = 'A4';
    $page_copies = (int)($_POST['page_copies'] ?? 1); if ($page_copies < 1) $page_copies = 1;
    $page_color_mode = ($_POST['page_color_mode'] ?? 'BW') === 'COLOR' ? 'COLOR' : 'BW';
    $page_align_mode = $_POST['page_align_mode'] ?? 'RTL';
    if (!in_array($page_align_mode, ['RTL','LTR','CENTER'], true)) $page_align_mode = 'RTL';
    $page_mt = max(0,(int)($_POST['page_margin_top'] ?? 5));
    $page_mr = max(0,(int)($_POST['page_margin_right'] ?? 5));
    $page_mb = max(0,(int)($_POST['page_margin_bottom'] ?? 5));
    $page_ml = max(0,(int)($_POST['page_margin_left'] ?? 5));

    $invoice_printer = trim($_POST['invoice_printer'] ?? '');
    $invoice_paper = $_POST['invoice_paper'] ?? '80mm';
    if (!in_array($invoice_paper, ['80mm','58mm'], true)) $invoice_paper = '80mm';
    $invoice_copies = (int)($_POST['invoice_copies'] ?? 1); if ($invoice_copies < 1) $invoice_copies = 1;
    $invoice_color_mode = ($_POST['invoice_color_mode'] ?? 'BW') === 'COLOR' ? 'COLOR' : 'BW';
    $invoice_align_mode = $_POST['invoice_align_mode'] ?? 'RTL';
    if (!in_array($invoice_align_mode, ['RTL','LTR','CENTER'], true)) $invoice_align_mode = 'RTL';
    $invoice_mt = max(0,(int)($_POST['invoice_margin_top'] ?? 5));
    $invoice_mr = max(0,(int)($_POST['invoice_margin_right'] ?? 5));
    $invoice_mb = max(0,(int)($_POST['invoice_margin_bottom'] ?? 5));
    $invoice_ml = max(0,(int)($_POST['invoice_margin_left'] ?? 5));
    $invoice_show_logo = isset($_POST['invoice_show_logo']) ? 1 : 0;
    $invoice_show_qr = isset($_POST['invoice_show_qr']) ? 1 : 0;
    $invoice_footer_note = trim($_POST['invoice_footer_note'] ?? '');
  $invoice_qr_template = trim($_POST['invoice_qr_template'] ?? '');
    if (strlen($invoice_qr_template) > 2000) $invoice_qr_template = substr($invoice_qr_template,0,2000);
  }

  if ($host === '') {
    $err = 'حدد جهاز الطباعة (Agent Host) أولاً.';
  } else {
    if ($kind === 'page') {
      $payload = [
        'page_agent_host' => $page_agent_host,
        'page_printer' => $page_printer,
        'page_paper' => $page_paper,
        'page_copies' => $page_copies,
        'page_color_mode' => $page_color_mode,
        'page_align_mode' => $page_align_mode,
        'page_margin_top' => $page_mt,
        'page_margin_right' => $page_mr,
        'page_margin_bottom' => $page_mb,
        'page_margin_left' => $page_ml,
      ];
    } else {
      $payload = [
        'invoice_agent_host' => $invoice_agent_host,
        'invoice_printer' => $invoice_printer,
        'invoice_paper' => $invoice_paper,
        'invoice_copies' => $invoice_copies,
        'invoice_color_mode' => $invoice_color_mode,
        'invoice_align_mode' => $invoice_align_mode,
        'invoice_margin_top' => $invoice_mt,
        'invoice_margin_right' => $invoice_mr,
        'invoice_margin_bottom' => $invoice_mb,
        'invoice_margin_left' => $invoice_ml,
        'invoice_show_logo' => $invoice_show_logo,
        'invoice_show_qr' => $invoice_show_qr,
        'invoice_footer_note' => $invoice_footer_note,
        'invoice_qr_template' => $invoice_qr_template,
      ];
    }

    if (save_device_defaults($conn, $host, $kind, $payload)) {
      $msg = 'تم حفظ الإعدادات كافتراضية لهذا الجهاز ✅';
    } else {
      $err = 'تعذر حفظ الإعدادات لهذا الجهاز.';
    }
  }
}

// تحميل الإعدادات الحالية
$ps = @$conn->query('SELECT * FROM print_settings WHERE id=1')->fetch_assoc() ?: [];

// ✅ تطبيق إعدادات الجهاز الافتراضية إن وجدت
$pageHost = (string)($ps['page_agent_host'] ?? '');
$invHost  = (string)($ps['invoice_agent_host'] ?? '');
if ($pageHost && function_exists('get_device_defaults')) {
  $d = get_device_defaults($conn, $pageHost, 'page');
  if ($d) $ps = array_merge($ps, $d);
}
if ($invHost && function_exists('get_device_defaults')) {
  $d = get_device_defaults($conn, $invHost, 'invoice');
  if ($d) $ps = array_merge($ps, $d);
}


// apply device defaults (إذا تم تحديد Agent Host)
$pageHostNow = (string)($ps['page_agent_host'] ?? '');
$invHostNow  = (string)($ps['invoice_agent_host'] ?? '');
if ($pageHostNow) {
  $d = get_device_defaults($conn, $pageHostNow, 'page');
  if ($d) $ps = array_merge($ps, $d);
}
if ($invHostNow) {
  $d = get_device_defaults($conn, $invHostNow, 'invoice');
  if ($d) $ps = array_merge($ps, $d);
}

$pageHost = trim((string)($ps['page_agent_host'] ?? '127.0.0.1'));
$invHost  = trim((string)($ps['invoice_agent_host'] ?? '127.0.0.1'));

if (!defined('UA_EMBED')) include __DIR__ . '/header.php';
if (!defined('UA_EMBED')) include __DIR__ . '/sidebar.php';

$active_tab = 'print';
if ($uaAndroidSettingsPrint) { require __DIR__ . '/android_settings_print.php'; 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"><?= t('إعدادات الطباعة') ?></h1>
      <a href="dashboard.php" class="btn btn-secondary"><i class="fa fa-arrow-right"></i> <?= t('رجوع') ?></a>
    </div>
  </section>

  <section class="content">
    <div class="container-fluid">
      <?php if (!defined('UA_EMBED') || !UA_EMBED) require __DIR__ . '/settings_tabs.php'; ?>

      <?php if($msg){ ?><div class="alert alert-success"><?= h($msg) ?></div><?php } ?>
      <?php if($err){ ?><div class="alert alert-danger"><?= h($err) ?></div><?php } ?>

      <form method="post" class="row">

        <!-- ✅ الطابعة الرئيسية -->
        <div class="col-lg-6">
          <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
              <b>الطابعة الرئيسية (A4 / التقارير)</b>
              <span class="badge badge-light" id="page_agent_status">Agent: ...</span>
            </div>
            <div class="card-body">

              <div class="sp-device-row">
                <div class="form-group">
                  <label>جهاز الطباعة (Agent Host/IP)</label>
                  <input class="form-control" name="page_agent_host" id="page_agent_host" value="<?= h($pageHost) ?>" oninput="setPreviewHost('page')" placeholder="مثال: 127.0.0.1 أو 192.168.1.20">
                  <small class="text-muted">يجب تشغيل Print Agent على هذا الجهاز والمنفذ 9123.</small>
                </div>

                <div class="form-group">
                  <label>الطابعة</label>
                  <select class="form-control" name="page_printer" id="page_printer_select">
                    <option value=""><?= h(($ps['page_printer'] ?? '') ?: '-- اختر طابعة --') ?></option>
                  </select>
                  <small class="text-muted">القائمة تأتي من طابعات ويندوز على الجهاز المحدد عبر Agent.</small>
                </div>
              </div>

              <div class="row">
                <div class="col-md-4">
                  <label>قياس الورق</label>
                  <select class="form-control" name="page_paper">
                    <?php $pp = $ps['page_paper'] ?? 'A4'; ?>
                    <option value="A4" <?= $pp==='A4'?'selected':'' ?>>A4</option>
                    <option value="A5" <?= $pp==='A5'?'selected':'' ?>>A5</option>
                    <option value="Letter" <?= $pp==='Letter'?'selected':'' ?>>Letter</option>
                  </select>
                </div>
                <div class="col-md-4">
                  <label>عدد النسخ</label>
                  <input type="number" class="form-control" name="page_copies" min="1" value="<?= (int)($ps['page_copies'] ?? 1) ?>">
                </div>
                <div class="col-md-4">
                  <label>الوضع</label>
                  <?php $pcm = $ps['page_color_mode'] ?? 'BW'; ?>
                  <select class="form-control" name="page_color_mode">
                    <option value="BW" <?= $pcm==='BW'?'selected':'' ?>>أبيض وأسود</option>
                    <option value="COLOR" <?= $pcm==='COLOR'?'selected':'' ?>>ألوان</option>
                  </select>
                </div>
              </div>

              <div class="row mt-3">
                <div class="col-md-4">
                  <label>المحاذاة</label>
                  <?php $pam = $ps['page_align_mode'] ?? 'RTL'; ?>
                  <select class="form-control" name="page_align_mode">
                    <option value="RTL" <?= $pam==='RTL'?'selected':'' ?>>يمين (RTL)</option>
                    <option value="LTR" <?= $pam==='LTR'?'selected':'' ?>>يسار (LTR)</option>
                    <option value="CENTER" <?= $pam==='CENTER'?'selected':'' ?>>وسط</option>
                  </select>
                </div>

                <div class="col-md-8">
                  <label>الهوامش (mm)</label>
                  <div class="row">
                    <div class="col"><input type="number" class="form-control" name="page_margin_top" value="<?= (int)($ps['page_margin_top'] ?? 5) ?>" placeholder="أعلى"></div>
                    <div class="col"><input type="number" class="form-control" name="page_margin_right" value="<?= (int)($ps['page_margin_right'] ?? 5) ?>" placeholder="يمين"></div>
                    <div class="col"><input type="number" class="form-control" name="page_margin_bottom" value="<?= (int)($ps['page_margin_bottom'] ?? 5) ?>" placeholder="أسفل"></div>
                    <div class="col"><input type="number" class="form-control" name="page_margin_left" value="<?= (int)($ps['page_margin_left'] ?? 5) ?>" placeholder="يسار"></div>
                  </div>
                </div>
              </div>

              <div class="d-flex flex-wrap gap-2 mt-3">
                <button type="submit" class="btn btn-outline-success btn-sm" name="save_device_page" value="1" onclick="return confirm('حفظ إعدادات الطابعة الرئيسية كافتراضي لهذا الجهاز؟');">
                  <i class="fa fa-star"></i> حفظ كافتراضي للجهاز
                </button>
                <button type="button" class="btn btn-outline-primary btn-sm" onclick="testPrint('page')">
                  <i class="fa fa-print"></i> اختبار (طباعة صامتة)
                </button>
                <a class="btn btn-outline-secondary btn-sm" target="_blank" href="print_preview.php?type=page&print=1">
                  <i class="fa fa-window-restore"></i> اختبار (نافذة الطباعة)
                </a>
                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="reloadPreview('preview_page')">
                  <i class="fa fa-sync"></i> تحديث المعاينة
                </button>
              </div>

              <div class="mt-3 border rounded ua-u-frame-260">
                <iframe id="preview_page" src="print_preview.php?type=page&host=<?= urlencode((string)($ps['page_agent_host'] ?? '127.0.0.1')) ?>" class="ua-u-iframe-260"></iframe>
              </div>

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

        <!-- ✅ طابعة الفواتير -->
        <div class="col-lg-6">
          <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
              <b>طابعة الفواتير (حراري)</b>
              <span class="badge badge-light" id="inv_agent_status">Agent: ...</span>
            </div>
            <div class="card-body">

              <div class="sp-device-row">
                <div class="form-group">
                  <label>جهاز الطباعة (Agent Host/IP)</label>
                  <input class="form-control" name="invoice_agent_host" id="invoice_agent_host" value="<?= h($invHost) ?>" oninput="setPreviewHost('invoice')" placeholder="مثال: 127.0.0.1 أو 192.168.1.30">
                </div>

                <div class="form-group">
                  <label>الطابعة</label>
                  <select class="form-control" name="invoice_printer" id="invoice_printer_select">
                    <option value=""><?= h(($ps['invoice_printer'] ?? '') ?: '-- اختر طابعة --') ?></option>
                  </select>
                </div>
              </div>

              <div class="row">
                <div class="col-md-4">
                  <label>قياس الورق</label>
                  <?php $ip = $ps['invoice_paper'] ?? '80mm'; ?>
                  <select class="form-control" name="invoice_paper" id="invoice_paper">
                    <option value="80mm" <?= $ip==='80mm'?'selected':'' ?>>80mm</option>
                    <option value="58mm" <?= $ip==='58mm'?'selected':'' ?>>58mm</option>
                  </select>
                </div>
                <div class="col-md-4">
                  <label>عدد النسخ</label>
                  <input type="number" class="form-control" name="invoice_copies" min="1" value="<?= (int)($ps['invoice_copies'] ?? 1) ?>">
                </div>
                <div class="col-md-4">
                  <label>الوضع</label>
                  <?php $icm = $ps['invoice_color_mode'] ?? 'BW'; ?>
                  <select class="form-control" name="invoice_color_mode">
                    <option value="BW" <?= $icm==='BW'?'selected':'' ?>>أبيض وأسود</option>
                    <option value="COLOR" <?= $icm==='COLOR'?'selected':'' ?>>ألوان</option>
                  </select>
                </div>
              </div>

              <div class="row mt-3">
                <div class="col-md-4">
                  <label>المحاذاة</label>
                  <?php $iam = $ps['invoice_align_mode'] ?? 'RTL'; ?>
                  <select class="form-control" name="invoice_align_mode">
                    <option value="RTL" <?= $iam==='RTL'?'selected':'' ?>>يمين (RTL)</option>
                    <option value="LTR" <?= $iam==='LTR'?'selected':'' ?>>يسار (LTR)</option>
                    <option value="CENTER" <?= $iam==='CENTER'?'selected':'' ?>>وسط</option>
                  </select>
                </div>

                <div class="col-md-8">
                  <label>الهوامش (mm)</label>
                  <div class="row">
                    <div class="col"><input type="number" class="form-control" name="invoice_margin_top" value="<?= (int)($ps['invoice_margin_top'] ?? 5) ?>" placeholder="أعلى"></div>
                    <div class="col"><input type="number" class="form-control" name="invoice_margin_right" value="<?= (int)($ps['invoice_margin_right'] ?? 5) ?>" placeholder="يمين"></div>
                    <div class="col"><input type="number" class="form-control" name="invoice_margin_bottom" value="<?= (int)($ps['invoice_margin_bottom'] ?? 5) ?>" placeholder="أسفل"></div>
                    <div class="col"><input type="number" class="form-control" name="invoice_margin_left" value="<?= (int)($ps['invoice_margin_left'] ?? 5) ?>" placeholder="يسار"></div>
                  </div>
                </div>
              </div>

              <div class="mt-3">
                <div class="custom-control custom-checkbox">
                  <input type="checkbox" class="custom-control-input" id="invoice_show_logo" name="invoice_show_logo" <?= ((int)($ps['invoice_show_logo'] ?? 1)===1)?'checked':'' ?>>
                  <label class="custom-control-label" for="invoice_show_logo">إظهار شعار الشركة</label>
                </div>
                <div class="custom-control custom-checkbox mt-2">
                  <input type="checkbox" class="custom-control-input" id="invoice_show_qr" name="invoice_show_qr" <?= ((int)($ps['invoice_show_qr'] ?? 1)===1)?'checked':'' ?>>
                  <label class="custom-control-label" for="invoice_show_qr">إظهار QR</label>
                </div>
              </div>

              <div class="mt-3">
                <label>قالب QR (قابل للتعديل)</label>
                <textarea class="form-control" name="invoice_qr_template" rows="3" placeholder="مثال: INV:{invoice_id}|NAME:{customer}|AMT_SYP:{amount_syp}|AMT_USD:{amount_usd}|TEL:{company_phone}"><?= h($ps['invoice_qr_template'] ?? '') ?></textarea>
                <small class="text-muted">
                  متغيرات متاحة: <code>{invoice_id}</code> <code>{customer}</code> <code>{amount_syp}</code> <code>{amount_usd}</code> <code>{currency}</code> <code>{company}</code> <code>{company_phone}</code> <code>{date}</code>
                </small>
              </div>

              <div class="mt-3">
                <label>ملاحظة أسفل الفاتورة</label>
                <input class="form-control" name="invoice_footer_note" value="<?= h($ps['invoice_footer_note'] ?? '') ?>" placeholder="مثال: شكرًا لتعاملكم معنا">
              </div>

              <div class="d-flex flex-wrap gap-2 mt-3">
                <button type="submit" class="btn btn-outline-success btn-sm" name="save_device_invoice" value="1" onclick="return confirm('حفظ إعدادات طابعة الفواتير كافتراضي لهذا الجهاز؟');">
                  <i class="fa fa-star"></i> حفظ كافتراضي للجهاز
                </button>
                <button type="button" class="btn btn-outline-primary btn-sm" onclick="testPrint('invoice')">
                  <i class="fa fa-print"></i> اختبار (طباعة صامتة)
                </button>
                <a class="btn btn-outline-secondary btn-sm" target="_blank" href="print_preview.php?type=invoice&print=1">
                  <i class="fa fa-window-restore"></i> اختبار (نافذة الطباعة)
                </a>
                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="reloadPreview('preview_invoice')">
                  <i class="fa fa-sync"></i> تحديث المعاينة
                </button>
              </div>

              <div class="mt-3 border rounded ua-u-frame-320">
                <iframe id="preview_invoice" src="print_preview.php?type=invoice&host=<?= urlencode((string)($ps['invoice_agent_host'] ?? '127.0.0.1')) ?>" class="ua-u-iframe-320"></iframe>
              </div>

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

        <div class="col-12">
          <div class="card">
            <div class="card-body d-flex justify-content-between align-items-center">
              <div class="text-muted">
                <b>ملاحظة احترافية:</b> للطباعة الصامتة (اختيار الطابعة تلقائيًا) يجب تشغيل <code>Print Agent</code> على جهاز الطباعة.
              </div>
              <button class="btn btn-success" name="save" value="1"><i class="fa fa-save"></i> <?= t('حفظ') ?></button>
            </div>
          </div>
        </div>

      </form>

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

<script>
function agentUrl(host){ 
  host = (host || '127.0.0.1').trim();
  if(!host) host = '127.0.0.1';
  if(host.includes('http://') || host.includes('https://')) return host.replace(/\/+$/,'') + ':9123';
  // إذا كتب IP فقط
  return 'http://' + host.replace(/\/+$/,'') + ':9123';
}


function setPreviewHost(type){
  const isInvoice = (type==='invoice');
  const host = document.getElementById(isInvoice ? 'invoice_agent_host' : 'page_agent_host').value || '127.0.0.1';
  const fr = document.getElementById(isInvoice ? 'preview_invoice' : 'preview_page');
  if(!fr) return;
  const url = new URL(fr.src, window.location.href);
  url.searchParams.set('host', host.trim());
  url.searchParams.set('ts', Date.now().toString());
  fr.src = url.toString();
}

async function fetchPrinters(host, selectId, statusId, selectedValue){
  const base = agentUrl(host);
  const st = document.getElementById(statusId);
  try{
    const res = await fetch(base + '/printers', {cache:'no-store'});
    if(!res.ok) throw new Error('HTTP ' + res.status);
    const data = await res.json();
    const sel = document.getElementById(selectId);
    const current = selectedValue || sel.getAttribute('data-selected') || '';
    sel.innerHTML = '<option value=\"\">-- اختر طابعة --</option>';
    (data || []).forEach(p=>{
      const opt = document.createElement('option');
      opt.value = p;
      opt.textContent = p;
      if(current && current === p) opt.selected = true;
      sel.appendChild(opt);
    });
    st.className = 'badge badge-success';
    st.textContent = 'Agent: Online';
  }catch(e){
    st.className = 'badge badge-danger';
    st.textContent = 'Agent: Offline';
  }
}

function reloadPreview(id){
  const fr = document.getElementById(id);
  if(!fr) return;
  const url = new URL(fr.src, window.location.href);
  url.searchParams.set('ts', Date.now().toString());
  fr.src = url.toString();
}

async function testPrint(type){
  const isInvoice = (type === 'invoice');
  const host = document.getElementById(isInvoice ? 'invoice_agent_host' : 'page_agent_host').value;
  const printerSel = document.getElementById(isInvoice ? 'invoice_printer_select' : 'page_printer_select');
  const printer = printerSel.value || '';
  if(!host){ alert('حدد جهاز الطباعة (Agent Host)'); return; }
  if(!printer){ alert('اختر طابعة أولًا'); return; }

  const base = agentUrl(host);

  // جلب HTML من المعاينة
  const iframeId = isInvoice ? 'preview_invoice' : 'preview_page';
  const fr = document.getElementById(iframeId);
  let html = '';
  try{
    const res = await fetch(fr.src.replace(/&print=1/g,'') + '&raw=1', {cache:'no-store'});
    html = await res.text();
  }catch(e){
    alert('تعذر جلب نموذج المعاينة للطباعة.');
    return;
  }

  // عدد النسخ
  const copies = parseInt(document.querySelector(`input[name=\"${isInvoice?'invoice_copies':'page_copies'}\"]`).value || '1', 10) || 1;

  try{
    const res = await fetch(base + '/print', {
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body: JSON.stringify({ printer, copies, html })
    });
    if(!res.ok) throw new Error('HTTP ' + res.status);
    const out = await res.json().catch(()=>({ok:true}));
    if(out && out.ok){
      alert('تم إرسال أمر الطباعة ✅');
    }else{
      alert('فشل الطباعة: ' + (out && out.error ? out.error : 'غير معروف'));
    }
  }catch(e){
    alert('لا يمكن الوصول للـ Agent. تأكد أنه يعمل على الجهاز والمنفذ 9123.');
  }
}


document.addEventListener('DOMContentLoaded', ()=>{
  // تحميل قوائم الطابعات لكل قسم
  const pageHost = document.getElementById('page_agent_host');
  const invHost = document.getElementById('invoice_agent_host');

  // حفظ القيمة المختارة من السيرفر في attribute
  document.getElementById('page_printer_select').setAttribute('data-selected', <?= json_encode((string)($ps['page_printer'] ?? '')) ?>);
  document.getElementById('invoice_printer_select').setAttribute('data-selected', <?= json_encode((string)($ps['invoice_printer'] ?? '')) ?>);

  fetchPrinters(pageHost.value, 'page_printer_select', 'page_agent_status');
  fetchPrinters(invHost.value, 'invoice_printer_select', 'inv_agent_status');

  let timer = null;
  const onHostChange = () => {
    if(timer) clearTimeout(timer);
    timer = setTimeout(()=>{
      fetchPrinters(pageHost.value, 'page_printer_select', 'page_agent_status');
      fetchPrinters(invHost.value, 'invoice_printer_select', 'inv_agent_status');
    }, 450);
  };
  pageHost.addEventListener('input', onHostChange);
  invHost.addEventListener('input', onHostChange);
});
</script>

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