<?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 (isset($_GET['delete'])) {
  $id = (int)$_GET['delete'];
  $pdo->prepare("DELETE FROM purchase_invoices WHERE id=?")->execute([$id]);
  go('/wood-system/pages/purchases.php');
}

/* إضافة فاتورة مشتريات جديدة */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['update_id'])) {
  $supplier_id   = (int)post('supplier_id');
  $payment_type  = post('payment_type', 'كاش');
  $cashbox_id    = !empty($_POST['cashbox_id']) ? (int)$_POST['cashbox_id'] : null;
  $date          = post('date', date('Y-m-d'));
  $expense_type  = post('expense_type', 'بدون');
  $expense_amount= (float)post('expense_amount', 0);
  $note          = trim(post('note'));

  // إنشاء الفاتورة
  $pdo->prepare("INSERT INTO purchase_invoices (supplier_id, date, payment_type, cashbox_id, expense_type, expense_amount, note)
                 VALUES (?,?,?,?,?,?,?)")
      ->execute([$supplier_id, $date, $payment_type, $cashbox_id, $expense_type, $expense_amount, $note]);
  $invoice_id = $pdo->lastInsertId();

  // إدخال تفاصيل المنتجات + تحديث المخزون والتكلفة
  $items = $_POST['items'] ?? [];
  $total = 0;

  foreach ($items as $item) {
    $pid   = (int)$item['product_id'];
    $qty   = (float)$item['qty'];
    $price = (float)$item['price'];
    $line_total = $qty * $price;

    if ($pid && $qty > 0) {
      // 1. إضافة المنتج إلى جدول purchase_items
      $pdo->prepare("INSERT INTO purchase_items (invoice_id, product_id, qty, price, total)
                     VALUES (?,?,?,?,?)")->execute([$invoice_id, $pid, $qty, $price, $line_total]);

      // 2. جلب الكمية وسعر التكلفة الحالي
      $stmt = $pdo->prepare("SELECT quantity, cost_price FROM products WHERE id=?");
      $stmt->execute([$pid]);
      $product = $stmt->fetch();

      if ($product) {
        $old_qty  = (float)$product['quantity'];
        $old_cost = (float)$product['cost_price'];
        $new_qty  = $qty;
        $new_cost = $price;

        $total_qty = $old_qty + $new_qty;

        // 3. حساب المتوسط المرجح الجديد
        if ($total_qty > 0) {
          $weighted_cost = (($old_qty * $old_cost) + ($new_qty * $new_cost)) / $total_qty;
        } else {
          $weighted_cost = $new_cost;
        }

        // 4. تحديث الكمية وسعر التكلفة
        $pdo->prepare("UPDATE products SET quantity=?, cost_price=? WHERE id=?")
            ->execute([$total_qty, $weighted_cost, $pid]);
      }

      $total += $line_total;
    }
  }

  // تحديث الإجمالي مع المصروف
  $grand_total = $total + $expense_amount;
  $pdo->prepare("UPDATE purchase_invoices SET total=? WHERE id=?")->execute([$grand_total, $invoice_id]);

  // تحديث الصندوق إن وجد
  if ($cashbox_id && $payment_type === 'كاش') {
    $pdo->prepare("UPDATE cashbox SET balance = balance - ? WHERE id=?")->execute([$grand_total, $cashbox_id]);
    $note_utf8 = mb_convert_encoding("فاتورة مشتريات رقم $invoice_id", 'UTF-8', 'auto');
    $pdo->prepare("INSERT INTO cashbox_log (cashbox_id, type, amount, note)
                   VALUES (?,?,?,?)")->execute([$cashbox_id, 'withdraw', $grand_total, $note_utf8]);
  }

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

/* جلب البيانات */
$suppliers = $pdo->query("SELECT id,name FROM suppliers ORDER BY name")->fetchAll();
$products  = $pdo->query("SELECT id,name,price FROM products ORDER BY name")->fetchAll();
$cashboxes = $pdo->query("SELECT * FROM cashbox ORDER BY id")->fetchAll();
$invoices  = $pdo->query("
  SELECT pi.*, s.name AS supplier_name, c.name AS cashbox_name
  FROM purchase_invoices pi
  LEFT JOIN suppliers s ON s.id=pi.supplier_id
  LEFT JOIN cashbox c ON c.id=pi.cashbox_id
  ORDER BY pi.id DESC
")->fetchAll();
?>

<h3 class="mb-3">🧾 فواتير المشتريات</h3>

<div class="d-flex justify-content-end mb-3">
  <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addModal">➕ إضافة فاتورة جديدة</button>
</div>

<div class="card shadow-sm"><div class="card-body p-0">
<div class="table-responsive">
<table class="table table-striped text-center align-middle mb-0">
<thead class="table-dark">
<tr>
  <th>#</th><th>المورد</th><th>الصندوق</th><th>المبلغ ($)</th><th>المصاريف</th><th>الإجمالي ($)</th>
  <th>طريقة الدفع</th><th>التاريخ</th><th>ملاحظة</th><th>تحكم</th>
</tr>
</thead>
<tbody>
<?php foreach($invoices as $r): ?>
<?php $base_amount = $r['total'] - (float)$r['expense_amount']; ?>
<tr>
  <td><?= $r['id'] ?></td>
  <td><?= htmlspecialchars($r['supplier_name']) ?></td>
  <td><?= htmlspecialchars($r['cashbox_name'] ?? '-') ?></td>
  <td class="text-success fw-bold"><?= number_format($base_amount, 2) ?></td>
  <td><?= htmlspecialchars($r['expense_type']).' '.number_format($r['expense_amount'],2) ?></td>
  <td class="text-primary fw-bold"><?= number_format($r['total'],2) ?></td>
  <td><?= htmlspecialchars($r['payment_type']) ?></td>
  <td><?= htmlspecialchars($r['date']) ?></td>
  <td><?= htmlspecialchars($r['note']) ?></td>
  <td>
    <a href="purchase_view.php?id=<?= $r['id'] ?>" class="btn btn-sm btn-info">📄 عرض</a>
    <a href="?delete=<?= $r['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('هل أنت متأكد من الحذف؟')">🗑 حذف</a>
  </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div></div></div>

<!-- نافذة الإضافة -->
<div class="modal fade" id="addModal" tabindex="-1">
  <div class="modal-dialog modal-xl">
    <form method="post" class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title">🧾 إنشاء فاتورة مشتريات جديدة</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">

        <div class="row g-3 mb-3">
          <div class="col-md-4">
            <label class="form-label">المورد</label>
            <select name="supplier_id" class="form-select" required>
              <option value="">— اختر المورد —</option>
              <?php foreach($suppliers as $s): ?>
                <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['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="<?= date('Y-m-d') ?>">
          </div>
          <div class="col-md-3">
            <label class="form-label">طريقة الدفع</label>
            <select class="form-select" name="payment_type">
              <option value="كاش">كاش</option>
              <option value="آجل">آجل</option>
            </select>
          </div>
          <div class="col-md-2">
            <label class="form-label">الصندوق</label>
            <select name="cashbox_id" class="form-select">
              <option value="">— اختر —</option>
              <?php foreach($cashboxes as $cb): ?>
                <option value="<?= $cb['id'] ?>"><?= htmlspecialchars($cb['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>

        <table class="table table-bordered text-center align-middle" id="itemsTable">
          <thead class="table-dark">
            <tr><th>المنتج</th><th>الكمية</th><th>السعر</th><th>الإجمالي</th><th></th></tr>
          </thead>
          <tbody>
            <tr>
              <td>
                <select name="items[0][product_id]" class="form-select">
                  <?php foreach($products as $p): ?>
                    <option value="<?= $p['id'] ?>"><?= htmlspecialchars($p['name']) ?></option>
                  <?php endforeach; ?>
                </select>
              </td>
              <td><input type="number" step="0.01" name="items[0][qty]" class="form-control" value="1"></td>
              <td><input type="number" step="0.01" name="items[0][price]" class="form-control" value="0"></td>
              <td class="line-total">0.00</td>
              <td><button type="button" class="btn btn-danger btn-sm remove-row">✖</button></td>
            </tr>
          </tbody>
        </table>

        <button type="button" class="btn btn-secondary btn-sm mb-3" id="addRow">➕ إضافة منتج آخر</button>

        <div class="row g-3">
          <div class="col-md-4">
            <label class="form-label">نوع المصروف (اختياري)</label>
            <select name="expense_type" class="form-select">
              <option value="بدون">بدون</option>
              <option value="نقل">نقل</option>
              <option value="تخليص">تخليص</option>
              <option value="أخرى">أخرى</option>
            </select>
          </div>
          <div class="col-md-3">
            <label class="form-label">قيمة المصروف</label>
            <input type="number" step="0.01" class="form-control" name="expense_amount" value="0">
          </div>
          <div class="col-md-5">
            <label class="form-label">ملاحظات</label>
            <input class="form-control" name="note">
          </div>
        </div>

      </div>
      <div class="modal-footer">
        <button class="btn btn-primary px-4">💾 حفظ الفاتورة</button>
      </div>
    </form>
  </div>
</div>

<script>
let rowIndex = 1;
document.getElementById('addRow').onclick = function() {
  const tbody = document.querySelector('#itemsTable tbody');
  const newRow = tbody.rows[0].cloneNode(true);
  newRow.querySelectorAll('input, select').forEach(el => {
    el.name = el.name.replace('[0]', '['+rowIndex+']');
    if (el.tagName === 'INPUT') el.value = (el.classList.contains('qty') ? 1 : 0);
  });
  tbody.appendChild(newRow);
  rowIndex++;
};

document.addEventListener('click', e => {
  if (e.target.classList.contains('remove-row')) {
    e.target.closest('tr').remove();
  }
});
</script>

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