<?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['msg'])) {
  echo "<div class='alert alert-success text-center'>".$_SESSION['msg']."</div>";
  unset($_SESSION['msg']);
}

/* دالة post آمنة */
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'];

  // استرجاع بيانات الفاتورة
  $invoice = $pdo->prepare("SELECT * FROM sales_invoices WHERE id=?");
  $invoice->execute([$id]);
  $inv = $invoice->fetch();

  if ($inv) {
    // إعادة الكميات للمخزون
    $items = $pdo->prepare("SELECT product_id, qty FROM sales_items WHERE invoice_id=?");
    $items->execute([$id]);
    foreach ($items as $it) {
      $pdo->prepare("UPDATE products SET quantity = quantity + ? WHERE id=?")
          ->execute([$it['qty'], $it['product_id']]);
    }

    // خصم المبلغ من الصندوق في حال كانت كاش
    if (!empty($inv['cashbox_id']) && $inv['payment_type'] === 'كاش') {
      $pdo->prepare("UPDATE cashbox SET balance = balance - ? WHERE id=?")
          ->execute([$inv['total'], $inv['cashbox_id']]);
      $pdo->prepare("INSERT INTO cashbox_log (cashbox_id, type, amount, note)
                     VALUES (?,?,?,?)")->execute([$inv['cashbox_id'], 'سحب', $inv['total'], 'حذف فاتورة مبيعات رقم '.$id]);
    }

    // حذف البنود والفاتورة
    $pdo->prepare("DELETE FROM sales_items WHERE invoice_id=?")->execute([$id]);
    $pdo->prepare("DELETE FROM sales_invoices WHERE id=?")->execute([$id]);
  }

  header("Location: /wood-system/pages/sales.php");
  exit;
}

/* إضافة فاتورة جديدة */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['update_id'])) {
  $customer_id   = (int)post('customer_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_no    = trim(post('invoice_no'));
  $shipment_no   = trim(post('shipment_no'));
  $car_plate     = trim(post('car_plate'));
  $note          = trim(post('note'));

  // إنشاء الفاتورة
  $pdo->prepare("INSERT INTO sales_invoices (customer_id, date, payment_type, cashbox_id, invoice_no, shipment_no, car_plate, note, total)
                 VALUES (?,?,?,?,?,?,?,?,0)")
      ->execute([$customer_id, $date, $payment_type, $cashbox_id, $invoice_no, $shipment_no, $car_plate, $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 sales_items (invoice_id, product_id, qty, price, total)
                     VALUES (?,?,?,?,?)")->execute([$invoice_id, $pid, $qty, $price, $line_total]);
      $pdo->prepare("UPDATE products SET quantity = quantity - ? WHERE id=?")->execute([$qty, $pid]);
      $total += $line_total;
    }
  }

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

  // إيداع في الصندوق إن كانت كاش
  if ($cashbox_id && $payment_type === 'كاش') {
    $pdo->prepare("UPDATE cashbox SET balance = balance + ? WHERE id=?")->execute([$total, $cashbox_id]);
    $pdo->prepare("INSERT INTO cashbox_log (cashbox_id, type, amount, note)
                   VALUES (?,?,?,?)")->execute([$cashbox_id, 'إيداع', $total, 'فاتورة مبيعات رقم '.$invoice_id]);
  }

$_SESSION['msg'] = "✅ تم حفظ الفاتورة وتحديث المخزون والصندوق بنجاح.";
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}

/* جلب البيانات */
$customers = $pdo->query("SELECT id,name FROM customers 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 si.*, c.name AS customer_name, cb.name AS cashbox_name
  FROM sales_invoices si
  LEFT JOIN customers c ON c.id=si.customer_id
  LEFT JOIN cashbox cb ON cb.id=si.cashbox_id
  ORDER BY si.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 bg-gradient 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 sales_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_no'] ?: '-') ?></td>
              <td rowspan="<?= $rowspan ?>"><?= htmlspecialchars($r['shipment_no'] ?: '-') ?></td>
              <td rowspan="<?= $rowspan ?>"><?= htmlspecialchars($r['car_plate'] ?: '-') ?></td>
              <td rowspan="<?= $rowspan ?>"><?= htmlspecialchars($r['customer_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 ?>"><?= htmlspecialchars($r['date']) ?></td>
                      <td rowspan="<?= $rowspan ?>"><?= htmlspecialchars($r['note'] ?: '-') ?></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><?= htmlspecialchars($r['date']) ?></td>
                <td><?= htmlspecialchars($r['note'] ?: '-') ?></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">
      <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="customer_id" class="form-select" required>
              <option value="">— اختر العميل —</option>
              <?php foreach($customers as $c): ?>
                <option value="<?= $c['id'] ?>"><?= 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="<?= 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>

        <div class="row g-3 mb-3">
          <div class="col-md-4"><label class="form-label">رقم الفاتورة</label><input class="form-control" name="invoice_no"></div>
          <div class="col-md-4"><label class="form-label">رقم الإرسالية</label><input class="form-control" name="shipment_no"></div>
          <div class="col-md-4"><label class="form-label">لوحة السيارة</label><input class="form-control" name="car_plate"></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-12">
            <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'; ?>
