<?php
// sales_view.php
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/src/auth.php';
require_login();

function esc($v) {
    return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8');
}

$lang = $_GET['lang'] ?? 'en';
$is_ar = $lang === 'ar';
$dir = $is_ar ? 'rtl' : 'ltr';

$id = intval($_GET['id'] ?? 0);
if(!$id) die($is_ar ? 'فاتورة غير موجودة' : 'Invoice not found');

// fetch sale
$stmt = $pdo->prepare("SELECT s.*, c.name as customer_name FROM sales s LEFT JOIN customers c ON s.customer_id = c.id WHERE s.id = ?");
$stmt->execute([$id]);
$sale = $stmt->fetch(PDO::FETCH_ASSOC);
if(!$sale) die($is_ar ? 'فاتورة غير موجودة' : 'Invoice not found');

// fetch items + SKU
$items = $pdo->prepare("
    SELECT si.*, p.name_ar, p.name_en, p.sku
    FROM sale_items si 
    LEFT JOIN products p ON si.product_id = p.id
    WHERE si.sale_id = ?
");
$items->execute([$id]);
$rows = $items->fetchAll(PDO::FETCH_ASSOC);

$user_display = $_SESSION['display_name'] ?? $_SESSION['username'] ?? 'User';
?>
<!doctype html>
<html lang="<?= $is_ar ? 'ar' : 'en' ?>" dir="<?= $dir ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= $is_ar ? 'عرض الفاتورة' : 'View Invoice' ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body{font-family:'Tajawal',sans-serif;background:#f8f9fa}
.card{border-radius:12px;box-shadow:0 4px 12px rgba(0,0,0,0.05)}
@media print {.no-print{display:none}}
</style>
</head>
<body class="p-3">
<div class="container">
  <div class="card p-3 mb-3">

    <div class="d-flex justify-content-between align-items-center">
      <h4><?= $is_ar ? 'فاتورة بيع' : 'Sales Invoice' ?></h4>
      <div class="text-end">
        <div><?= $is_ar ? 'فاتورة #' : 'Invoice #' ?> <?= esc($sale['invoice_no']) ?></div>
        <div class="text-muted"><?= date('Y-m-d H:i', strtotime($sale['created_at'])) ?></div>
      </div>
    </div>

    <hr>

    <div class="row mb-3">
      <div class="col-md-6">
        <strong><?= $is_ar ? 'العميل' : 'Customer' ?>:</strong> 
        <?= esc($sale['customer_name'] ?? ($is_ar ? 'نقدي' : 'Cash')) ?><br>

        <strong><?= $is_ar ? 'طريقة الدفع' : 'Payment Method' ?>:</strong> 
        <?= esc($sale['payment_method']) ?><br>

<strong><?= $is_ar ? 'ملاحظة' : 'Note' ?>:</strong>
<?= esc(($sale['note'] ?? '') !== '' ? $sale['note'] : ($is_ar ? '— لا توجد —' : '— None —')) ?><br>

      </div>

      <div class="col-md-6 text-md-end">
        <strong><?= $is_ar ? 'أُنشِئت بواسطة' : 'Created by' ?>:</strong> 
        <?= esc($user_display) ?><br>
      </div>
    </div>

    <div class="table-responsive">
      <table class="table table-bordered">
        <thead class="table-light">
          <tr>
            <th><?= $is_ar ? 'الصنف' : 'Item' ?></th>
            <th class="text-center"><?= $is_ar ? 'الكمية' : 'Qty' ?></th>
            <th class="text-end"><?= $is_ar ? 'سعر الوحدة' : 'Unit Price' ?></th>
            <th class="text-end"><?= $is_ar ? 'الإجمالي' : 'Subtotal' ?></th>
          </tr>
        </thead>
        <tbody>
          <?php foreach($rows as $r): 
            $label = $is_ar ? ($r['name_ar'] ?: $r['name_en']) : ($r['name_en'] ?: $r['name_ar']);
          ?>
            <tr>
              <td>
                <?= esc($label ?: ('#'.$r['product_id'])) ?>
                <br>
                <small class="text-muted">SKU: <?= esc($r['sku'] ?? '') ?></small>
              </td>
              <td class="text-center"><?= number_format($r['qty'],2) ?></td>
              <td class="text-end"><?= number_format($r['unit_price'],2) ?></td>
              <td class="text-end"><?= number_format($r['subtotal'],2) ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>

        <tfoot>
          <tr>
            <th colspan="3" class="text-end"><?= $is_ar ? 'المجموع' : 'Total' ?></th>
            <th class="text-end"><?= number_format($sale['total'],2) ?></th>
          </tr>
          <tr>
            <th colspan="3" class="text-end"><?= $is_ar ? 'المدفوع' : 'Paid' ?></th>
            <th class="text-end"><?= number_format($sale['paid'],2) ?></th>
          </tr>
          <tr>
            <th colspan="3" class="text-end"><?= $is_ar ? 'المتبقي' : 'Remaining' ?></th>
            <th class="text-end"><?= number_format($sale['total'] - $sale['paid'],2) ?></th>
          </tr>
          <tr>
            <th colspan="3" class="text-end"><?= $is_ar ? 'الربح' : 'Profit' ?></th>
            <th class="text-end"><?= number_format($sale['profit'],2) ?></th>
          </tr>
        </tfoot>

      </table>
    </div>

    <div class="d-flex justify-content-between align-items-center no-print mt-3">
      <div>
        <a href="sales_create.php?lang=<?= esc($lang) ?>" class="btn btn-outline-secondary"><?= $is_ar ? 'فاتورة جديدة' : 'New Sale' ?></a>
        <a href="sales_list.php?lang=<?= esc($lang) ?>" class="btn btn-outline-secondary"><?= $is_ar ? 'قائمة الفواتير' : 'Sales List' ?></a>
      </div>
      <div>
        <button class="btn btn-primary" onclick="window.print()"><?= $is_ar ? 'طباعة' : 'Print' ?></button>
      </div>
    </div>

  </div>
</div>
</body>
</html>
