<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_save_path(__DIR__ . '/../tmp');
if (!is_dir(__DIR__ . '/../tmp')) mkdir(__DIR__ . '/../tmp', 0777, true);
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: /wood-system/login.php");
    exit;
}

require __DIR__ . '/../includes/db.php';
require __DIR__ . '/../includes/header.php';

if (!function_exists('post')) {
  function post($key, $default=null){ return $_POST[$key] ?? $default; }
}
if (!function_exists('go')) {
  function go($url){ header("Location: $url"); exit; }
}

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$id) die("رقم فاتورة غير صالح.");

// حفظ التعديلات
if ($_SERVER['REQUEST_METHOD'] === 'POST' && post('form_name')==='edit_invoice') {
  $customer_id = (int)post('customer_id');
  $invoice_no  = trim(post('invoice_no'));
  $shipment_no = trim(post('shipment_no'));
  $car_plate   = trim(post('car_plate'));
  $payment_type= post('payment_type','كاش');
  $date        = post('date', date('Y-m-d'));
  $items       = post('items', []);

  // تنظيف العناصر
  $clean = [];
  foreach ($items as $it) {
    $pid = isset($it['product_id']) ? (int)$it['product_id'] : 0;
    $qty = isset($it['qty']) ? (float)$it['qty'] : 0;
    $prc = isset($it['price']) ? (float)$it['price'] : 0;
    if ($pid > 0 && $qty > 0) $clean[] = ['product_id'=>$pid,'qty'=>$qty,'price'=>$prc];
  }
  if (!$customer_id || empty($clean)) {
    die("يرجى اختيار عميل وإضافة منتج واحد على الأقل.");
  }

  $pdo->beginTransaction();
  try {
    // إعادة مخزون البنود القديمة
    $old_items = $pdo->prepare("SELECT product_id, qty FROM invoice_items WHERE invoice_id=?");
    $old_items->execute([$id]);
    foreach ($old_items as $it) {
      $pdo->prepare("UPDATE products SET quantity = quantity + ? WHERE id=?")
          ->execute([$it['qty'], $it['product_id']]);
    }
    // حذف البنود القديمة
    $pdo->prepare("DELETE FROM invoice_items WHERE invoice_id=?")->execute([$id]);

    // تحديث رأس الفاتورة
    $pdo->prepare("UPDATE invoices SET customer_id=?, invoice_no=?, shipment_no=?, car_plate=?, payment_type=?, date=? WHERE id=?")
        ->execute([$customer_id,$invoice_no,$shipment_no,$car_plate,$payment_type,$date,$id]);

    // إدخال البنود الجديدة وتخفيض المخزون
    $total = 0;
    $ins = $pdo->prepare("INSERT INTO invoice_items (invoice_id, product_id, qty, price) VALUES (?,?,?,?)");
    $dec = $pdo->prepare("UPDATE products SET quantity = quantity - ? WHERE id=?");

    foreach ($clean as $it) {
      $ins->execute([$id, $it['product_id'], $it['qty'], $it['price']]);
      $dec->execute([$it['qty'], $it['product_id']]);
      $total += $it['qty'] * $it['price'];
    }

    // تحديث الإجمالي
    $pdo->prepare("UPDATE invoices SET total=? WHERE id=?")->execute([$total, $id]);

    $pdo->commit();
  } catch (Exception $e) {
    $pdo->rollBack();
    die("خطأ حفظ الفاتورة: " . $e->getMessage());
  }

  go('/wood-system/pages/sales.php');
}

/* جلب بيانات الفاتورة */
$invoice = $pdo->prepare("SELECT * FROM invoices WHERE id=?");
$invoice->execute([$id]);
$inv = $invoice->fetch(PDO::FETCH_ASSOC);
if (!$inv) die("الفاتورة غير موجودة.");

/* جلب العملاء والمنتجات */
$customers = $pdo->query("SELECT id, name FROM customers ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
$products  = $pdo->query("SELECT id, name FROM products ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

/* جلب البنود */
$items = $pdo->prepare("
  SELECT it.*, p.name AS product_name
  FROM invoice_items it
  LEFT JOIN products p ON p.id=it.product_id
  WHERE it.invoice_id=?
");
$items->execute([$id]);
$items = $items->fetchAll(PDO::FETCH_ASSOC);

// تحضير خيارات المنتجات HTML
ob_start();
?>
<?php foreach($products as $p): ?>
  <option value="<?= $p['id'] ?>"><?= htmlspecialchars($p['name']) ?></option>
<?php endforeach; ?>
<?php
$productOptions = trim(ob_get_clean());
?>

<h3 class="mb-3">📝 تعديل الفاتورة #<?= $inv['id'] ?></h3>

<div class="card shadow-sm">
  <div class="card-body">
    <form method="post">
      <input type="hidden" name="form_name" value="edit_invoice">

      <div class="row g-3 mb-3">
        <div class="col-md-4">
          <label class="form-label">العميل *</label>
          <select class="form-select" name="customer_id" required>
            <option value="">— اختر العميل —</option>
            <?php foreach($customers as $c): ?>
              <option value="<?= $c['id'] ?>" <?= $c['id']==$inv['customer_id']?'selected':'' ?>>
                <?= htmlspecialchars($c['name']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-3">
          <label class="form-label">التاريخ</label>
          <input type="date" class="form-control" name="date" value="<?= htmlspecialchars($inv['date']) ?>">
        </div>
        <div class="col-md-2">
          <label class="form-label">طريقة الدفع</label>
          <select class="form-select" name="payment_type">
            <option value="كاش" <?= $inv['payment_type']=='كاش'?'selected':'' ?>>كاش</option>
            <option value="آجل" <?= $inv['payment_type']=='آجل'?'selected':'' ?>>آجل</option>
          </select>
        </div>
        <div class="col-md-3">
          <label class="form-label">رقم الفاتورة</label>
          <input class="form-control" name="invoice_no" value="<?= htmlspecialchars($inv['invoice_no']) ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">رقم الإرسالية</label>
          <input class="form-control" name="shipment_no" value="<?= htmlspecialchars($inv['shipment_no']) ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">لوحة السيارة</label>
          <input class="form-control" name="car_plate" value="<?= htmlspecialchars($inv['car_plate']) ?>">
        </div>
      </div>

      <div class="table-responsive">
        <table class="table table-bordered align-middle text-center" id="itemsTable">
          <thead class="table-light">
            <tr>
              <th style="width:40%">المنتج</th>
              <th style="width:15%">الكمية</th>
              <th style="width:15%">السعر</th>
              <th style="width:15%">الإجمالي</th>
              <th style="width:15%">—</th>
            </tr>
          </thead>
          <tbody id="itemsBody">
            <?php foreach($items as $it): ?>
              <tr>
                <td>
                  <select name="items[][product_id]" class="form-select" required>
                    <option value="">— اختر المنتج —</option>
                    <?php foreach($products as $p): ?>
                      <option value="<?= $p['id'] ?>" <?= $p['id']==$it['product_id']?'selected':'' ?>>
                        <?= htmlspecialchars($p['name']) ?>
                      </option>
                    <?php endforeach; ?>
                  </select>
                </td>
                <td><input type="number" name="items[][qty]" class="form-control item-qty" step="0.01" min="0.01" value="<?= (float)$it['qty'] ?>"></td>
                <td><input type="number" name="items[][price]" class="form-control item-price" step="0.01" min="0" value="<?= (float)$it['price'] ?>"></td>
                <td class="row-total">0.00</td>
                <td><button type="button" class="btn btn-danger btn-sm" onclick="removeRow(this)">🗑 حذف</button></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
          <tfoot>
            <tr>
              <td colspan="3" class="text-end fw-bold">الإجمالي الكلي:</td>
              <td><span id="grandTotal">0.00</span></td>
              <td></td>
            </tr>
          </tfoot>
        </table>
      </div>

      <button type="button" class="btn btn-outline-primary" onclick="addRow()">➕ إضافة منتج</button>

      <div class="mt-4 d-flex gap-2">
        <a href="/wood-system/pages/sales.php" class="btn btn-secondary">رجوع</a>
        <button class="btn btn-success">حفظ التعديلات</button>
      </div>
    </form>
  </div>
</div>

<script>
const productOptions = `<?= preg_replace('/\s+/', ' ', $productOptions) ?>`;

function addRow() {
  const tb = document.getElementById('itemsBody');
  const tr = document.createElement('tr');
  tr.innerHTML = `
    <td>
      <select name="items[][product_id]" class="form-select" required>
        <option value="">— اختر المنتج —</option>
        ${productOptions}
      </select>
    </td>
    <td><input type="number" name="items[][qty]" class="form-control item-qty" step="0.01" min="0.01" value="1"></td>
    <td><input type="number" name="items[][price]" class="form-control item-price" step="0.01" min="0" value="0"></td>
    <td class="row-total">0.00</td>
    <td><button type="button" class="btn btn-danger btn-sm" onclick="removeRow(this)">🗑 حذف</button></td>
  `;
  tb.appendChild(tr);
  attachRowEvents(tr);
  recalcTotals();
}

function removeRow(btn){
  btn.closest('tr').remove();
  recalcTotals();
}

function attachRowEvents(tr){
  const qty = tr.querySelector('.item-qty');
  const price = tr.querySelector('.item-price');
  qty.addEventListener('input', recalcTotals);
  price.addEventListener('input', recalcTotals);
}

function recalcTotals(){
  let grand = 0;
  document.querySelectorAll('#itemsBody tr').forEach(tr => {
    const q = parseFloat(tr.querySelector('.item-qty')?.value || 0);
    const p = parseFloat(tr.querySelector('.item-price')?.value || 0);
    const t = (q>0 && p>=0) ? (q*p) : 0;
    tr.querySelector('.row-total').textContent = t.toFixed(2);
    grand += t;
  });
  document.getElementById('grandTotal').textContent = grand.toFixed(2);
}

// حساب الإجماليات الابتدائية
document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('#itemsBody tr').forEach(attachRowEvents);
  recalcTotals();
});
</script>

<?php require __DIR__ . '/../includes/footer.php'; ?>
