<?php
// admin/print_invoice.php
// FINAL: طباعة فاتورة نظيفة + بدون أي اعتماد على أعمدة غير موجودة + بدون تعارض دوال helpers
// يدعم: paper=A4|80mm|58mm  و auto=1

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

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

// في بعض النسخ يوجد auth.php
if (file_exists(__DIR__ . '/auth.php')) {
  require_once __DIR__ . '/auth.php';
}

$conn = ensure_db(true);
if (!($conn instanceof mysqli)) {
  http_response_code(500);
  echo "DB connection failed";
  exit;
}

$outputActor = ua_output_session_actor($conn);
if (empty($outputActor['authorized'])) {
  if (function_exists('require_login')) {
    require_login();
    $outputActor = ua_output_session_actor($conn);
  }
}
if (empty($outputActor['authorized'])) {
  http_response_code(401);
  exit('AUTH_REQUIRED');
}
$requestedAgentId = (int)($_GET['agent'] ?? 0);
if (($outputActor['type'] ?? '') === 'agent' && $requestedAgentId !== (int)$outputActor['id']) {
  http_response_code(403);
  exit('AGENT_SCOPE_MISMATCH');
}
$outputScopeKey = (string)$outputActor['scope'];

/**
 * ملاحظة: لا نستخدم SHOW TABLES/SHOW COLUMNS مع placeholders
 * لأن بعض نسخ MariaDB/PHP قد لا تدعمها مع prepare.
 * لذلك نعتمد information_schema (مضمون مع prepare).
 */

function pickv(array $row, array $keys, $default='') {
  foreach ($keys as $k) {
    if (array_key_exists($k, $row) && $row[$k] !== '' && $row[$k] !== null) return $row[$k];
  }
  return $default;
}

// -------- Inputs ----------
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$paper = $_GET['paper'] ?? 'A4';
$paper = in_array($paper, ['A4','80mm','58mm'], true) ? $paper : 'A4';
$auto = !empty($_GET['auto']);
$silent = !empty($_GET['silent']);

if ($id <= 0) {
  http_response_code(400);
  echo "Invalid invoice id";
  exit;
}

// -------- Determine invoice table ----------
$invoiceTable = null;
foreach (['invoices', 'billing_invoices', 'isp_invoices'] as $t) {
  if (table_exists($conn, $t)) { $invoiceTable = $t; break; }
}
if (!$invoiceTable) $invoiceTable = 'invoices';

// -------- Load invoice (prepared) ----------
$st = $conn->prepare("SELECT * FROM `$invoiceTable` WHERE id = ? LIMIT 1");
if (!$st) {
  http_response_code(500);
  echo "Prepare failed for invoice table.";
  exit;
}
$st->bind_param("i", $id);
$st->execute();
$r = $st->get_result();
$inv = $r ? $r->fetch_assoc() : null;
$st->close();

if (!$inv) {
  http_response_code(404);
  echo "Invoice not found";
  exit;
}

// -------- Resolve subscriber id (flex) ----------
$subId = (int) pickv($inv, ['subscriber_id','sub_id','customer_id','client_id','user_id'], 0);

// -------- Load subscriber (no joins, only existing cols) ----------
$sub = [];
if ($subId > 0 && table_exists($conn, 'subscribers')) {

  $subTable = 'subscribers';

  // فقط الأعمدة الموجودة فعليًا
  $wanted = [
    'id',
    'name','full_name','customer_name',
    'phone','mobile',
    'pppoe_username','username',
    'package','package_name',
    'speed','speed_name'
  ];

  $cols = [];
  foreach ($wanted as $c) {
    if (col_exists($conn, $subTable, $c)) $cols[] = "`$c`";
  }

  $sel = $cols ? implode(',', $cols) : '*';

  $st = $conn->prepare("SELECT $sel FROM `$subTable` WHERE id = ? LIMIT 1");
  if ($st) {
    $st->bind_param("i", $subId);
    $st->execute();
    $res = $st->get_result();
    $sub = $res ? ($res->fetch_assoc() ?: []) : [];
    $st->close();
  }
}

// -------- Values ----------
$invNo   = pickv($inv, ['invoice_no','number','id'], (string)$id);
$invDate = pickv($inv, ['invoice_date','created_at','date','created_on'], date('Y-m-d H:i:s'));
$amount  = pickv($inv, ['amount','total','final_total','price'], '0.00');
$status  = pickv($inv, ['status','state','paid_status'], '');

$customerName = pickv($sub, ['full_name','customer_name','name'], pickv($inv, ['customer_name','name'], ''));
$phone        = pickv($sub, ['mobile','phone'], pickv($inv, ['phone'], ''));
$username     = pickv($sub, ['pppoe_username','username'], pickv($inv, ['username'], ''));
$package      = pickv($sub, ['package_name','package'], pickv($inv, ['package','package_name'], ''));
$speed        = pickv($sub, ['speed_name','speed'], pickv($inv, ['speed','speed_name'], ''));

$by = $_SESSION['admin_username'] ?? ($_SESSION['admin_user'] ?? 'Admin');
if (($outputActor['type'] ?? '') === 'agent') {
  $agentIdForName = (int)$outputActor['id'];
  $agentNameResult = @$conn->query("SELECT name FROM agents WHERE id={$agentIdForName} LIMIT 1");
  if ($agentNameResult && ($agentNameRow = $agentNameResult->fetch_assoc())) {
    $by = trim((string)($agentNameRow['name'] ?? '')) ?: ('معتمد #' . $agentIdForName);
  }
}

// -------- Paper width ----------
$w = '210mm';
if ($paper === '80mm') $w = '80mm';
if ($paper === '58mm') $w = '58mm';
$paperClass = 'ua-invoice-paper-a4';
if ($paper === '80mm') $paperClass = 'ua-invoice-paper-80';
if ($paper === '58mm') $paperClass = 'ua-invoice-paper-58';

?><!doctype html>
<?php $uaLang = function_exists('current_lang') ? current_lang() : 'ar'; $uaDir = ($uaLang === 'en') ? 'ltr' : 'rtl'; ?>
<html lang="<?= h($uaLang) ?>" dir="<?= h($uaDir) ?>">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>طباعة فاتورة #<?= h($invNo) ?></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 ?>">
  
</head>
<body class="ua-special-page ua-print-page ua-print-invoice-page ua-print-standalone">

<div class="bar ua-print-toolbar">
  <div class="ua-u-fw-900">فاتورة #<?= h($invNo) ?></div>
  <div class="ua-print-toolbar-actions">
    <button class="btn" type="button" onclick="history.back()">رجوع</button>
    <button class="btn primary" type="button" onclick="window.print()">طباعة</button>
  </div>
</div>

<div class="wrap ua-print-wrap">
  <div class="paper ua-print-sheet <?= h($paperClass) ?>">
    <div class="head ua-print-sheet-head">
      <p class="title ua-print-sheet-title">فاتورة</p>
      <p class="sub ua-print-sheet-sub">رقم: <?= h($invNo) ?> • <?= h($invDate) ?></p>
    </div>

    <div class="grid ua-print-sheet-grid">
      <div class="row ua-print-sheet-row"><span class="k ua-print-k">العميل</span><span class="v ua-print-v"><?= h($customerName) ?></span></div>
      <?php if ($username !== ''): ?>
        <div class="row ua-print-sheet-row"><span class="k ua-print-k">اسم المستخدم</span><span class="v ua-print-v"><?= h($username) ?></span></div>
      <?php endif; ?>
      <?php if ($phone !== ''): ?>
        <div class="row ua-print-sheet-row"><span class="k ua-print-k">الهاتف</span><span class="v ua-print-v"><?= h($phone) ?></span></div>
      <?php endif; ?>
      <?php if ($package !== ''): ?>
        <div class="row ua-print-sheet-row"><span class="k ua-print-k">الباقة</span><span class="v ua-print-v"><?= h($package) ?></span></div>
      <?php endif; ?>
      <?php if ($speed !== ''): ?>
        <div class="row ua-print-sheet-row"><span class="k ua-print-k">السرعة</span><span class="v ua-print-v"><?= h($speed) ?></span></div>
      <?php endif; ?>
      <div class="row ua-print-sheet-row"><span class="k ua-print-k">المبلغ</span><span class="v ua-print-v"><?= h($amount) ?></span></div>
      <?php if ($status !== ''): ?>
        <div class="row ua-print-sheet-row"><span class="k ua-print-k">الحالة</span><span class="v ua-print-v"><?= h($status) ?></span></div>
      <?php endif; ?>
    </div>

    <div class="foot ua-print-sheet-foot">
      <span>طُبع بواسطة: <?= h($by) ?></span>
      <span><?= h(date('Y-m-d H:i')) ?></span>
    </div>
  </div>
</div>

<?php if ($silent): ?><script>window.UA_OUTPUT_SILENT=true;</script><?php endif; ?>
<?php ua_output_print_bootstrap($conn, $paper === 'A4' ? 'invoice_a4' : 'invoice_thermal', (string)$id, $outputScopeKey); ?>
<?php if ($auto): ?>
<script>
  setTimeout(function(){ window.print(); }, 250);
</script>
<?php endif; ?>


<?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>
