<?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 (empty($_SESSION['form_token'])) {
  $_SESSION['form_token'] = bin2hex(random_bytes(16));
}

if (!function_exists('post')) {
  function post($key, $default = null) {
    return isset($_POST[$key]) ? trim($_POST[$key]) : $default;
  }
}

/* حذف فاتورة */
if (isset($_GET['delete'])) {
  $id = (int)$_GET['delete'];
  $pdo->prepare("DELETE FROM purchase_items WHERE invoice_id=?")->execute([$id]);
  $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'])) {

  // 🔒 تحقق من الرمز لمنع التكرار
  if (!isset($_POST['form_token']) || $_POST['form_token'] !== $_SESSION['form_token']) {
    exit("<div class='alert alert-danger text-center'>⚠️ العملية مكررة أو انتهت صلاحيتها.</div>");
  }
  unset($_SESSION['form_token']); // إبطال الرمز بعد استخدامه

  $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'));
  $invoice_number = post('invoice_number');
  $shipping_number= post('shipping_number');
  $car_plate      = post('car_plate');
  $expense_type   = post('expense_type', 'بدون');
  $expense_amount = (float)post('expense_amount', 0);
  $extra_expenses = (float)post('extra_expenses', 0);
  $note           = trim(post('note'));

  // إنشاء الفاتورة
  $pdo->prepare("INSERT INTO purchase_invoices 
    (supplier_id, date, payment_type, cashbox_id, invoice_number, shipping_number, car_plate, expense_type, expense_amount, extra_expenses, note, total)
    VALUES (?,?,?,?,?,?,?,?,?,?,?,0)")
      ->execute([$supplier_id, $date, $payment_type, $cashbox_id, $invoice_number, $shipping_number, $car_plate, $expense_type, $expense_amount, $extra_expenses, $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) {
      $pdo->prepare("INSERT INTO purchase_items (invoice_id, product_id, qty, price, total)
                     VALUES (?,?,?,?,?)")->execute([$invoice_id, $pid, $qty, $price, $line_total]);

      // 🔹 جلب بيانات المنتج القديمة
      $stmt = $pdo->prepare("SELECT quantity, cost_price FROM products WHERE id=?");
      $stmt->execute([$pid]);
      $old = $stmt->fetch(PDO::FETCH_ASSOC);
      $old_qty  = $old['quantity'] ?? 0;
      $old_cost = $old['cost_price'] ?? 0;

      // 🔹 حساب التكلفة المتوسطة الجديدة
      $total_qty = $old_qty + $qty;
      if ($total_qty > 0) {
        $new_cost = (($old_qty * $old_cost) + ($qty * $price)) / $total_qty;
      } else {
        $new_cost = $price;
      }

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

      $total += $line_total;
    }
  }

  // تحديث الإجمالي
  $grand_total = $total + $expense_amount + $extra_expenses;
  $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]);
    $pdo->prepare("INSERT INTO cashbox_log (cashbox_id, type, amount, note)
                   VALUES (?,?,?,?)")->execute([$cashbox_id, 'withdraw', $grand_total, 'فاتورة مشتريات رقم '.$invoice_id]);
  }

  echo "<div class='alert alert-success text-center'>✅ تم حفظ الفاتورة وتحديث المخزون بنجاح.</div>";

  // 🆕 إنشاء رمز جديد بعد كل عملية ناجحة
  $_SESSION['form_token'] = bin2hex(random_bytes(16));
}

/* جلب البيانات */
$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-lg border-0 rounded-4">
  <div class="card-header bg-primary text-white py-3 d-flex justify-content-between align-items-center">
    <h5 class="mb-0">🧾 فواتير المشتريات (كاملة التفاصيل)</h5>
    <button class="btn btn-light btn-sm fw-bold" data-bs-toggle="modal" data-bs-target="#addModal">➕ إضافة فاتورة جديدة</button>
  </div>

  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-bordered align-middle text-center 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>
            <th>المصاريف</th>
            <th>التاريخ</th>
            <th>تحكم</th>
          </tr>
        </thead>
        <tbody>
          <?php if (empty($invoices)): ?>
            <tr><td colspan="13" class="text-muted py-4">لا توجد فواتير حتى الآن</td></tr>
          <?php else: ?>
            <?php foreach($invoices as $r): ?>
              <?php
                $stmt = $pdo->prepare("
                  SELECT p.name AS product_name, i.qty, i.price, i.total
                  FROM purchase_items i
                  LEFT JOIN products p ON p.id = i.product_id
                  WHERE i.invoice_id = ?
                ");
                $stmt->execute([$r['id']]);
                $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
                $rowspan = count($items) ?: 1;
              ?>
              <tr class="<?= ($r['payment_type'] === 'آجل' ? 'table-warning' : ''); ?>">
                <td rowspan="<?= $rowspan ?>"><?= htmlspecialchars($r['invoice_number'] ?: '-') ?></td>
                <td rowspan="<?= $rowspan ?>"><?= htmlspecialchars($r['shipping_number'] ?: '-') ?></td>
                <td rowspan="<?= $rowspan ?>"><?= htmlspecialchars($r['car_plate'] ?: '-') ?></td>
                <td rowspan="<?= $rowspan ?>"><?= htmlspecialchars($r['supplier_name'] ?: '-') ?></td>
                <td rowspan="<?= $rowspan ?>">
                  <?= $r['payment_type'] === 'كاش'
                      ? '<span class="badge bg-success">كاش</span>'
                      : '<span class="badge bg-warning text-dark">آجل</span>'; ?>
                </td>
                <td rowspan="<?= $rowspan ?>"><?= htmlspecialchars($r['cashbox_name'] ?? '-') ?></td>

                <?php if (!empty($items)): ?>
                  <?php $first = true; foreach ($items as $it): ?>
                    <?php if (!$first) echo "<tr>"; ?>
                      <td><?= htmlspecialchars($it['product_name']) ?></td>
                      <td><?= $it['qty'] ?></td>
                      <td><?= number_format($it['price'],2) ?></td>
                      <td><?= number_format($it['total'],2) ?></td>
                      <?php if ($first): ?>
                        <td rowspan="<?= $rowspan ?>">
                          <?= ($r['expense_amount'] > 0 || $r['extra_expenses'] > 0)
                                ? htmlspecialchars($r['expense_type']).' '.number_format($r['expense_amount'] + $r['extra_expenses'],2)
                                : '-' ?>
                        </td>
                        <td rowspan="<?= $rowspan ?>"><?= htmlspecialchars($r['date']) ?></td>
                        <td rowspan="<?= $rowspan ?>">
                          <a href="?delete=<?= $r['id'] ?>" class="btn btn-sm btn-danger"
                             onclick="return confirm('هل أنت متأكد من الحذف؟')">🗑</a>
                        </td>
                      <?php endif; ?>
                    </tr>
                    <?php $first = false; ?>
                  <?php endforeach; ?>
                <?php else: ?>
                  <td colspan="4" class="text-muted">لا توجد مواد</td>
                  <td><?= ($r['expense_amount'] > 0 || $r['extra_expenses'] > 0)
                          ? htmlspecialchars($r['expense_type']).' '.number_format($r['expense_amount'] + $r['extra_expenses'],2)
                          : '-' ?></td>
                  <td><?= htmlspecialchars($r['date']) ?></td>
                  <td>
                    <a href="?delete=<?= $r['id'] ?>" class="btn btn-sm btn-danger"
                       onclick="return confirm('هل أنت متأكد من الحذف؟')">🗑</a>
                  </td>
                <?php endif; ?>
            <?php endforeach; ?>
          <?php endif; ?>
        </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">
      <input type="hidden" name="form_token" value="<?= $_SESSION['form_token'] ?>">
      <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-3">
            <label class="form-label">رقم الفاتورة</label>
            <input name="invoice_number" class="form-control">
          </div>
          <div class="col-md-3">
            <label class="form-label">رقم الإرسالية</label>
            <input name="shipping_number" class="form-control">
          </div>
          <div class="col-md-3">
            <label class="form-label">لوحة السيارة</label>
            <input name="car_plate" class="form-control">
          </div>
          <div class="col-md-3">
            <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>

        <div class="row g-3 mb-3">
          <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-3">
            <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-3">
            <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-3">
            <label class="form-label">مصاريف إضافية</label>
            <input type="number" step="0.01" class="form-control" name="extra_expenses" value="0">
          </div>
          <div class="col-md-3">
            <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 = 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'; ?>
