<?php
// invoice_view.php
// Displays a purchase OR sale invoice (auto-detects available tables).
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/src/auth.php';
require_login();

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

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

$lang = $_GET['lang'] ?? ($_SESSION['lang'] ?? 'en');
if (isset($_GET['lang'])) { $_SESSION['lang'] = $_GET['lang'] === 'ar' ? 'ar' : 'en'; $lang = $_SESSION['lang']; }
$is_ar = $lang === 'ar';

// invoice id and optional type from query string
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$requested_type = isset($_GET['type']) ? strtolower($_GET['type']) : ''; // 'purchase' or 'sale' optional

if ($id <= 0) {
    echo ($is_ar ? 'معرف الفاتورة غير صالح.' : 'Invalid invoice id.');
    exit;
}

// helper: check table exists
function table_exists($pdo, $name){
    try {
        $res = $pdo->query("SHOW TABLES LIKE " . $pdo->quote($name))->fetchColumn();
        return (bool)$res;
    } catch (Exception $e) { return false; }
}

// decide whether to show purchase or sale
$has_purchases = table_exists($pdo, 'purchases') && table_exists($pdo, 'purchase_items');
$has_sales = table_exists($pdo, 'sales') && table_exists($pdo, 'sale_items');

$type = null;
if ($requested_type === 'purchase' && $has_purchases) $type = 'purchase';
elseif ($requested_type === 'sale' && $has_sales) $type = 'sale';
else {
    // auto-pick
    if ($has_purchases) $type = 'purchase';
    elseif ($has_sales) $type = 'sale';
    else {
        echo ($is_ar ? 'لا توجد جداول الفواتير (purchases أو sales) في قاعدة البيانات.' : 'No invoice tables (purchases or sales) found in database.');
        exit;
    }
}

$invoice = null;
$items = [];
$partner_name = '';
$total = 0;
$paid = 0;
$created_at = '';
$note = '';

try {
    if ($type === 'purchase') {
        // fetch purchase header: adjust columns if your schema differs
        $stmt = $pdo->prepare("SELECT p.*, COALESCE(s.name,'') AS supplier_name
                               FROM purchases p
                               LEFT JOIN suppliers s ON s.id = p.supplier_id
                               WHERE p.id = ? LIMIT 1");
        $stmt->execute([$id]);
        $invoice = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$invoice) {
            echo ($is_ar ? 'فاتورة المشتريات غير موجودة.' : 'Purchase invoice not found.');
            exit;
        }
        $partner_name = $invoice['supplier_name'] ?? ($is_ar ? 'مورد غير معروف' : 'Unknown supplier');
        $total = floatval($invoice['total'] ?? 0);
        $created_at = $invoice['created_at'] ?? '';
        $note = $invoice['note'] ?? '';
        // items
        $stmt = $pdo->prepare("SELECT pi.*, COALESCE(p.sku,'') AS sku, COALESCE(p.name_en,p.name_ar,p.name,'') AS product_name
                               FROM purchase_items pi
                               LEFT JOIN products p ON p.id = pi.product_id
                               WHERE pi.purchase_id = ?");
        $stmt->execute([$id]);
        $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } else {
        // sale
        $stmt = $pdo->prepare("SELECT s.*, COALESCE(c.name,'') AS customer_name
                               FROM sales s
                               LEFT JOIN customers c ON c.id = s.customer_id
                               WHERE s.id = ? LIMIT 1");
        $stmt->execute([$id]);
        $invoice = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$invoice) {
            echo ($is_ar ? 'فاتورة المبيعات غير موجودة.' : 'Sale invoice not found.');
            exit;
        }
        $partner_name = $invoice['customer_name'] ?? ($is_ar ? 'عميل غير معروف' : 'Unknown customer');
        $total = floatval($invoice['total'] ?? 0);
        $paid = floatval($invoice['paid'] ?? 0);
        $created_at = $invoice['created_at'] ?? '';
        $note = $invoice['note'] ?? ($invoice['payment_method'] ?? '');
        $stmt = $pdo->prepare("SELECT si.*, COALESCE(p.sku,'') AS sku, COALESCE(p.name_en,p.name_ar,p.name,'') AS product_name
                               FROM sale_items si
                               LEFT JOIN products p ON p.id = si.product_id
                               WHERE si.sale_id = ?");
        $stmt->execute([$id]);
        $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Exception $e) {
    echo ($is_ar ? 'خطأ في استعلام قاعدة البيانات: ' : 'Database error: ') . esc($e->getMessage());
    exit;
}

// compute sums (in case items have subtotal)
$calc_total = 0;
foreach ($items as $it) {
    // possible fields: qty, cost, subtotal, unit_price
    $qty = isset($it['qty']) ? floatval($it['qty']) : (isset($it['sale_qty'])?floatval($it['sale_qty']):0);
    $unit = null;
    if (isset($it['subtotal'])) $calc_total += floatval($it['subtotal']);
    else {
        // prefer cost for purchases, unit_price for sales
        if ($type === 'purchase') $unit = isset($it['cost']) ? floatval($it['cost']) : 0;
        else $unit = isset($it['unit_price']) ? floatval($it['unit_price']) : (isset($it['subtotal']) && $qty ? floatval($it['subtotal'])/$qty : 0);
        $calc_total += $qty * ($unit ?? 0);
    }
}

// If header total is empty or differs, prefer calculated
if (empty($total) || abs($total - $calc_total) > 0.01) $total = $calc_total;

?>
<!doctype html>
<html lang="<?= $is_ar ? 'ar' : 'en' ?>" dir="<?= $is_ar ? 'rtl' : 'ltr' ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= $is_ar ? 'عرض الفاتورة' : 'Invoice View' ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body{background:#f8fafc;padding:18px;font-family:Inter,Arial,sans-serif}
.invoice-card{max-width:900px;margin:auto;background:#fff;padding:20px;border-radius:10px;box-shadow:0 6px 18px rgba(0,0,0,0.06)}
.table thead th{background:#f3f6f9}
.header-row{display:flex;justify-content:space-between;align-items:center;gap:12px}
.header-left h4{margin:0}
.small-muted{color:#6c757d}
@media print{ .no-print{display:none!important} }
</style>
</head>
<body>
<div class="invoice-card">
  <div class="header-row mb-3">
    <div class="header-left">
      <h4><?= $is_ar ? ($type==='purchase' ? 'فاتورة مشتريات' : 'فاتورة مبيعات') : ($type==='purchase' ? 'Purchase Invoice' : 'Sales Invoice') ?></h4>
      <div class="small-muted"><?= $is_ar ? 'الطرف' : 'Partner' ?>: <strong><?= esc($partner_name) ?></strong></div>
      <div class="small-muted"><?= $is_ar ? 'التاريخ' : 'Date' ?>: <?= esc($created_at) ?></div>
    </div>
    <div class="header-right text-end no-print">
      <a href="purchase_invoice.php" class="btn btn-outline-secondary btn-sm"><?= $is_ar ? 'رجوع' : 'Back' ?></a>
      <button onclick="window.print()" class="btn btn-dark btn-sm"><?= $is_ar ? 'طباعة' : 'Print' ?></button>
    </div>
  </div>

  <?php if ($note): ?>
    <div class="mb-2"><strong><?= $is_ar ? 'ملاحظة:' : 'Note:' ?></strong> <?= esc($note) ?></div>
  <?php endif; ?>

  <div class="table-responsive">
    <table class="table table-bordered">
      <thead>
        <tr>
          <th>#</th>
          <th><?= $is_ar ? 'المنتج' : 'Product' ?></th>
          <th>SKU</th>
          <th><?= $is_ar ? 'الكمية' : 'Qty' ?></th>
          <th><?= $is_ar ? ($type==='purchase' ? 'سعر التكلفة' : 'Unit Price') : 'Unit Price' ?></th>
          <th><?= $is_ar ? 'المجموع' : 'Subtotal' ?></th>
        </tr>
      </thead>
      <tbody>
        <?php
        $i=1;
        foreach ($items as $it):
            $qty = isset($it['qty']) ? floatval($it['qty']) : 0;
            $unit = 0;
            if ($type === 'purchase') {
                $unit = isset($it['cost']) ? floatval($it['cost']) : 0;
            } else {
                $unit = isset($it['unit_price']) ? floatval($it['unit_price']) : (isset($it['subtotal']) && $qty? floatval($it['subtotal'])/$qty : 0);
            }
            $subtotal = isset($it['subtotal']) ? floatval($it['subtotal']) : ($qty * $unit);
        ?>
        <tr>
          <td><?= $i++ ?></td>
          <td><?= esc($it['product_name'] ?? ($it['name'] ?? '')) ?></td>
          <td><?= esc($it['sku'] ?? '') ?></td>
          <td><?= number_format($qty, 2) ?></td>
          <td><?= number_format($unit, 2) ?></td>
          <td><?= number_format($subtotal, 2) ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
      <tfoot>
        <tr>
          <th colspan="5" class="text-end"><?= $is_ar ? 'الإجمالي' : 'Total' ?></th>
          <th><?= number_format($total, 2) ?></th>
        </tr>
        <?php if ($type==='sale'): ?>
          <tr>
            <th colspan="5" class="text-end"><?= $is_ar ? 'مدفوع' : 'Paid' ?></th>
            <th><?= number_format($paid, 2) ?></th>
          </tr>
        <?php endif; ?>
      </tfoot>
    </table>
  </div>
  <div class="small-muted text-end mt-2"><?= $is_ar ? 'توليد الفاتورة' : 'Invoice generated' ?> — <?= date('Y-m-d H:i') ?></div>
</div>
</body>
</html>
