<?php $title='عرض الفاتورة'; include __DIR__.'/../layout/header.php'; ?>
<?php
$logo = trim((string)setting('logo_path', ''));
$logoUrl = $logo !== '' ? file_url($logo) : '';

$embeddedHeaderPath = __DIR__ . '/Fakhar.jpeg';
$embeddedStampPath  = __DIR__ . '/Stamp.jpeg';

$headerImageUrl = '';
if (is_file($embeddedHeaderPath)) {
    $headerImageUrl = 'data:image/jpeg;base64,' . base64_encode((string)file_get_contents($embeddedHeaderPath));
} else {
    $headerSetting = trim((string)setting('invoice_header_image', ''));
    if ($headerSetting !== '') {
        $headerImageUrl = file_url($headerSetting);
    } else {
        $headerImageUrl = $logoUrl;
    }
}

/* Stamp image */
$stampImageUrl = '';
if (is_file($embeddedStampPath)) {
    $stampImageUrl = 'data:image/jpeg;base64,' . base64_encode((string)file_get_contents($embeddedStampPath));
} else {
    $stampSetting = trim((string)setting('invoice_stamp_image', ''));
    if ($stampSetting !== '') {
        $stampImageUrl = file_url($stampSetting);
    } else {
        $stampImageUrl = $logoUrl;
    }
}

$customerName   = (string)($invoice['customer_name'] ?? '');
$customerPhone  = (string)($invoice['customer_phone'] ?? '');
$customerCivil  = (string)($invoice['customer_civil_id'] ?? '');
$deliveryDate   = (string)($invoice['delivery_date'] ?? '');
$returnDate     = (string)($invoice['return_date'] ?? '');
$employeeName   = (string)($invoice['created_by_name'] ?? '');
$invoiceNo      = (string)($invoice['invoice_no'] ?? '');
$signatureData  = (string)($invoice['signature_data'] ?? '');

$totals = [
    'grand'   => number_format((float)($invoice['grand_total'] ?? 0), 3),
    'paid'    => number_format((float)($invoice['paid_total'] ?? 0), 3),
    'balance' => number_format((float)($invoice['balance_due'] ?? 0), 3),
];

$displayRows = [];
foreach (($lines ?? []) as $line) {
    $title = trim((string)($line['category_name'] ?? ''));
    if ($title === '') {
        $title = ((string)($line['line_type'] ?? '') === 'sale') ? 'أغراض مباعة' : 'أغراض مؤجرة';
    }

    $itemCode = trim((string)($line['item_code'] ?? ''));
    $itemName = trim((string)($line['item_name'] ?? ''));
    $qty = (int)($line['quantity'] ?? 1);
    $unitPrice = (float)($line['unit_price'] ?? 0);
    $finalPrice = (float)($line['final_price'] ?? 0);
    $lineType = (string)($line['line_type'] ?? 'rental');

    $descParts = [];
    if ($itemCode !== '') $descParts[] = 'الكود: ' . $itemCode;
    if ($itemName !== '') $descParts[] = $itemName;
    $description = implode(' - ', $descParts);

    $displayRows[] = [
        'title' => $title,
        'description' => $description,
        'type_label' => $lineType === 'sale' ? 'بيع' : 'إيجار',
        'qty' => $qty,
        'unit_price' => number_format($unitPrice, 3),
        'final_price' => number_format($finalPrice, 3),
    ];
}
?>
<style>
:root{
  --gold:#b79633;
  --gold-dark:#a88528;
  --ink:#2c2c2c;
  --line:#4a4a4a;
  --soft:#f8f6f2;
}
html,body{
  background:#ececec !important;
  margin:0;
  padding:0;
}
body{
  font-family:"Tahoma","Arial",sans-serif;
  color:var(--ink);
  -webkit-print-color-adjust:exact !important;
  print-color-adjust:exact !important;
}
.no-print-toolbar{
  display:flex;
  justify-content:space-between;
  align-items:center;
  gap:12px;
  flex-wrap:wrap;
  margin-bottom:10px;
}
.invoice-a4-page{
  width:210mm;
  height:297mm;
  margin:0 auto;
  background:#fff;
  color:var(--ink);
  position:relative;
  box-shadow:0 10px 30px rgba(0,0,0,.08);
  border:1px solid #ddd;
  padding:8mm 9mm 7mm;
  overflow:hidden;
  box-sizing:border-box;
}
.invoice-a4-page::before,
.invoice-a4-page::after{
  content:"";
  position:absolute;
  width:18px;
  height:18px;
  border:1.5px solid #666;
}
.invoice-a4-page::before{top:8px;left:8px;border-right:none;border-bottom:none}
.invoice-a4-page::after{top:8px;right:8px;border-left:none;border-bottom:none}

.page-inner{
  position:relative;
  z-index:2;
  display:flex;
  flex-direction:column;
  height:100%;
}

.brand-watermark{
  position:absolute;
  inset:0;
  pointer-events:none;
  z-index:1;
}
.brand-watermark img{
  position:absolute;
  width:56%;
  left:50%;
  top:48%;
  transform:translate(-50%,-50%);
  opacity:.08;
}
.header-image-wrap{
  margin:-1mm -1mm 3mm;
  text-align:center;
  flex:0 0 auto;
}
.header-image{
  display:block;
  width:100%;
  height:auto;
  object-fit:contain;
  max-height:60mm;
}
.form-block{
  display:grid;
  gap:6px;
  margin-bottom:8px;
  flex:0 0 auto;
}
.form-label{
  font-size:12px;
  font-weight:900;
  text-align:right;
  white-space:nowrap;
}
.form-value{
  min-height:16px;
  border-bottom:1px dotted #555;
  display:flex;
  align-items:flex-end;
  padding:0 4px 2px;
  font-size:12px;
  font-weight:700;
}
.items-area{
  margin-top:6px;
  direction:rtl;
  flex:1 1 auto;
}
.items-table{
  width:100%;
  border-collapse:separate;
  border-spacing:0 5px;
  table-layout:fixed;
}
.items-table th{
  background:#2f333b;
  color:#fff;
  padding:6px 8px;
  font-size:12px;
  font-weight:900;
  text-align:center;
  line-height:1.2;
}
.items-table th:first-child{
  border-top-right-radius:10px;border-bottom-right-radius:10px;
}
.items-table th:last-child{
  border-top-left-radius:10px;border-bottom-left-radius:10px;
}
.items-table td{
  background:var(--soft);
  border-top:1px solid #e7dfd3;
  border-bottom:1px solid #e7dfd3;
  padding:7px 8px;
  font-size:12px;
  vertical-align:middle;
  line-height:1.25;
}
.items-table tr td:first-child{
  border-right:1px solid #e7dfd3;
  border-top-right-radius:10px;
  border-bottom-right-radius:10px;
}
.items-table tr td:last-child{
  border-left:1px solid #e7dfd3;
  border-top-left-radius:10px;
  border-bottom-left-radius:10px;
}
.item-title{
  font-weight:800;
  color:#1f2937;
  font-size:11px;
  line-height:1.2;
}
.item-desc{
  color:#6b7280;
  font-size:10px;
  margin-top:2px;
  line-height:1.35;
}
.type-pill{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-width:52px;
  padding:4px 8px;
  border-radius:999px;
  font-size:10px;
  font-weight:800;
  line-height:1;
}
.type-pill.rental{background:#dbeafe;color:#1d4ed8}
.type-pill.sale{background:#dcfce7;color:#166534}
.num-cell{
  text-align:center;
  font-weight:800;
  white-space:nowrap;
  font-size:11px;
}
.money-cell{
  text-align:center;
  font-weight:900;
  color:#111827;
  white-space:nowrap;
  font-size:11px;
}
.summary-grid{
  display:grid;
  grid-template-columns:repeat(3,minmax(0,1fr));
  gap:8px;
  margin-top:8px;
}
.summary-card{
  background:#fff;
  border:1px solid #eadfd5;
  border-radius:12px;
  padding:8px;
  text-align:center;
}
.summary-card .label{
  font-size:10px;
  color:#8b7a6b;
  margin-bottom:4px;
}
.summary-card .value{
  font-size:12px;
  font-weight:800;
  color:#1f2937;
}
.summary-card.highlight{
  background:linear-gradient(135deg,var(--gold),var(--gold-dark));
}
.summary-card.highlight .label,
.summary-card.highlight .value{
  color:#fff;
}
.empty-items{
  background:#faf7f4;
  border:1px dashed #d7c9b6;
  border-radius:12px;
  padding:12px;
  text-align:center;
  color:#7c6d5a;
  font-weight:700;
  font-size:11px;
}

/* bottom section pinned to bottom */
.page-bottom{
  margin-top:auto;
  flex:0 0 auto;
}

.ack-wrap{
  text-align:center;
  margin-top:8px;
}
.ack-title{
  display:inline-block;
  background:#fff;
  border:2px solid var(--line);
  border-radius:10px;
  padding:2px 16px 3px;
  font-size:16px;
  font-weight:900;
  margin-bottom:-8px;
  position:relative;
  z-index:2;
}
.ack-box{
  border:2px solid var(--line);
  border-radius:12px;
  padding:10px 10px 8px;
  background:rgba(255,255,255,.78);
  font-size:9px;
  line-height:1.6;
  font-weight:700;
}
.note-box{
  margin-top:6px;
  background:var(--gold);
  color:#fff;
  border-radius:8px;
  padding:8px 10px;
  text-align:center;
  font-size:10px;
  font-weight:900;
  line-height:1.5;
}
.footer-signs{
  margin-top:5px;
  display:grid;
  grid-template-columns:1fr 1fr;
  gap:24px;
  align-items:end;
}
.sign-box{text-align:center}
.sign-title{
  font-size:13px;
  font-weight:900;
  margin-bottom:4px;
}
.sign-line{
  border-bottom:1px dotted #555;
  min-height:34px;
  display:flex;
  align-items:flex-end;
  justify-content:center;
  padding-bottom:2px;
}
.sign-line img{
  max-height:44px;
  object-fit:contain;
}
.sign-customer img{
  max-height:34px;
  max-width:160px;
}

@page{
  size:A4;
  margin:0;
}
@media print{
  html,body{
    width:210mm !important;
    height:297mm !important;
    min-width:210mm !important;
    max-width:210mm !important;
    background:#fff !important;
    margin:0 !important;
    padding:0 !important;
    overflow:hidden !important;
    
  }
  
  .no-print{
    display:none !important;
    visibility:hidden !important;
  }
  .invoice-a4-page{
    width:210mm !important;
    height:297mm !important;
    margin:0 !important;
    box-shadow:none !important;
    border:none !important;
    padding:8mm 9mm 14mm !important;
    overflow:hidden !important;
    box-sizing:border-box !important;
    page-break-after:avoid !important;
    page-break-before:avoid !important;
    page-break-inside:avoid !important;
    break-inside:avoid !important;
  }
  .page-inner{
    display:flex !important;
    flex-direction:column !important;
    height:100% !important;
  }
  .page-bottom{
    margin-top:auto !important;
    flex:0 0 auto !important;
  }
  .items-table{
    width:100% !important;
    border-collapse:separate !important;
    border-spacing:0 5px !important;
    table-layout:fixed !important;
  }
  .items-table thead{
    display:table-header-group !important;
  }
  .items-table tr{
    display:table-row !important;
    page-break-inside:avoid !important;
    break-inside:avoid !important;
  }
  .items-table th,
  .items-table td{
    display:table-cell !important;
    background:#f8f6f2 !important;
    box-shadow:none !important;
  }
  .items-table th{
    background:#2f333b !important;
    color:#fff !important;
  }
  .items-badge,
  .summary-card.highlight,
  .note-box{
    background:var(--gold) !important;
    color:#fff !important;
  }
  .summary-grid,
  .page-bottom,
  .ack-wrap,
  .note-box,
  .footer-signs{
    page-break-inside:avoid !important;
    break-inside:avoid !important;
  }
  .type-pill{
    border:1px solid transparent !important;
  }
  .type-pill.rental{
    background:#dbeafe !important;
    color:#1d4ed8 !important;
    border-color:#bfdbfe !important;
  }
  .type-pill.sale{
    background:#dcfce7 !important;
    color:#166534 !important;
    border-color:#bbf7d0 !important;
  }
}
</style>

<div class="no-print card">
  <div class="no-print-toolbar">
    <div>
      <h2 style="margin:0"><?= e($invoiceNo) ?></h2>
      <div class="muted">فاتورة / عقد تجهيز و تأجير</div>
    </div>
    <div class="toolbar">
      <a class="btn light" href="<?= e(base_url('?page=invoices')) ?>">العودة</a>
      <button class="btn secondary" onClick="window.print()">طباعة A4</button>
    </div>
  </div>
</div>

<div class="invoice-a4-page">
  <div class="brand-watermark">
    <?php if($logoUrl !== ''): ?><img src="<?= e($logoUrl) ?>" alt="wm"><?php endif; ?>
  </div>

  <div class="page-inner">
    <div class="header-image-wrap">
      <img class="header-image" src="<?= e($headerImageUrl) ?>" alt="header">
    </div>

    <div class="form-block">
      <table width="100%" border="0">
        <tr>
          <td width="9%"><div class="form-label">الاسم :</div></td>
          <td width="91%"><div class="form-value"><?= e($customerName) ?></div></td>
        </tr>
      </table>

      <table width="100%" border="0">
        <tr>
          <td width="23%"><div class="form-label">رقم البطاقة الشخصية :</div></td>
          <td width="77%"><div class="form-value"><?= e($customerCivil) ?></div></td>
        </tr>
      </table>

      <table width="100%" border="0">
        <tr>
          <td width="15%"><div class="form-label">رقم الهاتف :</div></td>
          <td width="35%"><div class="form-value"><?= e($customerPhone) ?></div></td>
          <td width="15%"><div class="form-label">أسم الموظف :</div></td>
          <td width="35%"><div class="form-value"><?= e($employeeName) ?></div></td>
        </tr>
      </table>

      <table width="100%" border="0">
        <tr>
          <td width="15%"><div class="form-label">تاريخ حجز الأغراض :</div></td>
          <td width="35%"><div class="form-value"><?= e($deliveryDate) ?></div></td>
          <td width="15%"><div class="form-label">تاريخ استرجاع الأغراض :</div></td>
          <td width="35%"><div class="form-value"><?= e($returnDate) ?></div></td>
        </tr>
      </table>
    </div>

    <div class="items-area">
      <?php if (!empty($displayRows)): ?>
      <table class="items-table">
        <thead>
          <tr>
            <th width="35%">القطعة / الفئة</th>
            <th width="15%">النوع</th>
            <th width="10%">الكمية</th>
            <th width="20%">سعر القطعة</th>
            <th width="20%">الإجمالي</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($displayRows as $row): ?>
          <tr>
            <td>
              <div class="item-title"><?= e($row['title']) ?></div>
              <?php if ($row['description'] !== ''): ?>
                <div class="item-desc"><?= e($row['description']) ?></div>
              <?php endif; ?>
            </td>
            <td class="num-cell">
              <span class="type-pill <?= $row['type_label'] === 'بيع' ? 'sale' : 'rental' ?>">
                <?= e($row['type_label']) ?>
              </span>
            </td>
            <td class="num-cell"><?= e((string)$row['qty']) ?></td>
            <td class="money-cell"><?= e($row['unit_price']) ?> ر.ع</td>
            <td class="money-cell"><?= e($row['final_price']) ?> ر.ع</td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
      <?php else: ?>
        <div class="empty-items">لا توجد عناصر مسجلة داخل هذه الفاتورة.</div>
      <?php endif; ?>

      <div class="summary-grid">
        <div class="summary-card">
          <div class="label">المبلغ المدفوع</div>
          <div class="value"><?= e($totals['paid']) ?> ر.ع</div>
        </div>
        <div class="summary-card highlight">
          <div class="label">إجمالي الفاتورة</div>
          <div class="value"><?= e($totals['grand']) ?> ر.ع</div>
        </div>
        <div class="summary-card">
          <div class="label">المبلغ المتبقي</div>
          <div class="value"><?= e($totals['balance']) ?> ر.ع</div>
        </div>
      </div>
    </div>

    <div class="page-bottom">
      <div class="ack-wrap">
        <span class="ack-title">إقرار</span>
        <div class="ack-box">
          أقر وأتعهد أنا المستأجر بإرجاع الأغراض كاملة وبحالة ممتازة وأتحمل كافة المسؤولية من خراب أو ضياع تجاه الأغراض وفي حالة عدم إرجاع الأغراض في الوقت المحدد سوف تُحسب قيمة إيجار المستلزمات المستأجرة عن كل يوم تأخير، وفي حالة ضياع أو إتلاف المصر والشال يُحسب بسعر ١٥ ريال، وفي حالة ضياع السيف ٥٠ ريال والخنجر بـ ٢٥ ريال، وضياع البشت ١٠٠ ريال والمسباح ٨ ريال.
        </div>
      </div>

      <div class="note-box">
        ملاحظة: زبوننا الكريم يرجى تجنب تبخير المصر وعمل الحناء الأسود على الرأس<br>
        في حالة عمل حناء يلغى الحجز أو يدفع مبلغ ضمان في حالة ضياع المصر
      </div>

      <div class="footer-signs">
        <div class="sign-box">
          <div class="sign-title">الختم</div>
          <div class="sign-line">
            <?php if($stampImageUrl !== ''): ?><img src="<?= e($stampImageUrl) ?>" alt="stamp"><?php endif; ?>
          </div>
        </div>
        <div class="sign-box sign-customer">
          <div class="sign-title">توقيع الزبون</div>
          <div class="sign-line">
            <?php if($signatureData !== ''): ?><img src="<?= e($signatureData) ?>" alt="signature"><?php endif; ?>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

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