<?php
$page_title = 'مشتريات جديدة';
$finance_active = 'purchases_new';
$finance_group = 'purchases';

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/purchases_lib.php';
require_once __DIR__ . '/finance_partners_lib.php';

require_login('login.php');
$conn = ensure_db(true);
if (function_exists('require_perm')) require_perm('can_manage_purchases');

ensure_purchase_tables($conn);
finance_partners_migrate($conn);

$err = '';
$supplier = trim((string)($_POST['supplier_name'] ?? ''));
$invoiceNo = trim((string)($_POST['invoice_no'] ?? ''));
$currency = strtoupper(trim((string)($_POST['currency'] ?? 'SYP')));
$usdRate = (float)($_POST['usd_rate'] ?? 0);
$paid = (float)($_POST['paid'] ?? 0);
$notes = trim((string)($_POST['notes'] ?? ''));
$accountingClass = strtoupper(trim((string)($_POST['accounting_class'] ?? 'OPERATING')));
$capitalMode = strtoupper(trim((string)($_POST['capital_allocation_mode'] ?? 'ONE')));
$capitalPartnerId = (int)($_POST['capital_partner_id'] ?? 0);
$capitalPartners = finance_partners_list($conn, true);
if (!in_array($accountingClass, ['OPERATING','CAPITAL'], true)) $accountingClass = 'OPERATING';
if (!in_array($capitalMode, ['ONE','ALL'], true)) $capitalMode = 'ONE';

if (!in_array($currency, ['SYP', 'USD'], true)) $currency = 'SYP';
if ($paid < 0) $paid = 0;
if ($usdRate < 0) $usdRate = 0;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_purchase'])) {
  $names = $_POST['item_name'] ?? [];
  $qtys = $_POST['qty'] ?? [];
  $prices = $_POST['unit_price'] ?? [];
  $items = [];
  $total = 0.0;

  if (!is_array($names)) $names = [];
  foreach ($names as $idx => $nameRaw) {
    $name = trim((string)$nameRaw);
    $qty = (float)($qtys[$idx] ?? 0);
    $price = (float)($prices[$idx] ?? 0);
    if ($name === '' && $qty <= 0 && $price <= 0) continue;
    if ($name === '' || $qty <= 0 || $price < 0) {
      $err = 'تأكد من اسم الصنف والكمية والسعر في كل سطر.';
      break;
    }
    $line = $qty * $price;
    $total += $line;
    $items[] = ['name' => $name, 'qty' => $qty, 'price' => $price, 'total' => $line];
  }

  if (!$err && !$items) {
    $err = 'أضف صنفاً واحداً على الأقل.';
  }
  if (!$err && $accountingClass === 'CAPITAL' && $currency === 'USD' && $usdRate <= 0) {
    $err = 'سعر الصرف مطلوب للمشتريات الرأسمالية بالدولار.';
  }

  if (!$err) {
    $conn->begin_transaction();
    $stmt = $conn->prepare("INSERT INTO shop_purchases (supplier_name, invoice_no, currency, usd_rate, total, paid, notes, accounting_class, capital_allocation_mode, capital_partner_id, created_at) VALUES (?,?,?,?,?,?,?,?,?,NULLIF(?,0),NOW())");
    if (!$stmt) {
      $err = 'تعذر تحضير فاتورة الشراء: ' . $conn->error;
    } else {
      $stmt->bind_param('sssdddsssi', $supplier, $invoiceNo, $currency, $usdRate, $total, $paid, $notes, $accountingClass, $capitalMode, $capitalPartnerId);
      if (!$stmt->execute()) {
        $err = 'تعذر حفظ فاتورة الشراء: ' . $stmt->error;
      } else {
        $purchaseId = (int)$stmt->insert_id;

        $itemStmt = $conn->prepare("INSERT INTO shop_purchase_items (purchase_id, item_name, qty, unit_price, total, created_at) VALUES (?,?,?,?,?,NOW())");
        if ($itemStmt) {
          foreach ($items as $it) {
            $itemName = $it['name'];
            $qty = (float)$it['qty'];
            $price = (float)$it['price'];
            $lineTotal = (float)$it['total'];
            $itemStmt->bind_param('isddd', $purchaseId, $itemName, $qty, $price, $lineTotal);
            if (!$itemStmt->execute()) { $err = $itemStmt->error; break; }
          }
          $itemStmt->close();
        }

        if (!$err && $accountingClass === 'CAPITAL') {
          $capitalValue = $currency === 'USD' ? round($total * $usdRate, 2) : round($total, 2);
          $capitalResult = finance_record_capital_purchase($conn, $purchaseId, $capitalValue, $capitalMode, $capitalPartnerId, (int)($_SESSION['admin_id'] ?? 0));
          if (empty($capitalResult['ok'])) $err = (string)($capitalResult['error'] ?? 'تعذر ترحيل الشراء إلى رأس المال.');
        }
        if (!$err) {
          $conn->commit();
          header('Location: purchases_view.php?id=' . $purchaseId);
          exit;
        }
      }
      if ($stmt instanceof mysqli_stmt) $stmt->close();
    }
    if ($err) @$conn->rollback();
  }
}
?>
<?php $UA_FORCE_DESIGN_V2 = true;
$uaAndroidPurchasesNew = ((string)($_GET['ua_android'] ?? '') === '1') || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidPurchasesNew) $UA_PAGE_CSS = ['assets/css/android_purchases_new.css']; ?>
<?php include __DIR__ . '/header.php'; ?>
<?php include __DIR__ . '/sidebar.php'; ?>
<div class="content-wrapper ua-extracted-page">
  <section class="content-header">
    <div class="container-fluid d-flex justify-content-between align-items-center flex-wrap gap-2">
      <h1 class="mb-0">مشتريات جديدة</h1>
      <a class="btn btn-secondary" href="purchases_report.php"><i class="fa fa-arrow-right"></i> رجوع</a>
    </div>
  </section>

  <section class="content">
    <div class="container-fluid">
      <?php include __DIR__ . '/finance_tabs.php'; ?>

      <?php if ($err): ?>
        <div class="alert alert-danger"><?= h($err) ?></div>
      <?php endif; ?>

      <form method="post" id="purchaseForm" autocomplete="off">
        <div class="card">
          <div class="card-header"><strong>بيانات الفاتورة</strong></div>
          <div class="card-body">
            <div class="row">
              <div class="col-md-4">
                <label>المورّد</label>
                <input class="form-control" name="supplier_name" value="<?= h($supplier) ?>">
              </div>
              <div class="col-md-3">
                <label>رقم الفاتورة</label>
                <input class="form-control" name="invoice_no" value="<?= h($invoiceNo) ?>">
              </div>
              <div class="col-md-2">
                <label>العملة</label>
                <select class="form-control" name="currency" id="currency">
                  <option value="SYP" <?= $currency === 'SYP' ? 'selected' : '' ?>>SYP</option>
                  <option value="USD" <?= $currency === 'USD' ? 'selected' : '' ?>>USD</option>
                </select>
              </div>
              <div class="col-md-3">
                <label>سعر الصرف</label>
                <input class="form-control" name="usd_rate" id="usdRate" type="number" min="0" step="0.01" value="<?= h((string)$usdRate) ?>">
              </div>
            </div>
            <hr>
            <div class="row">
              <div class="col-md-4">
                <label>التصنيف المحاسبي</label>
                <select class="form-control" name="accounting_class" id="accountingClass">
                  <option value="OPERATING" <?= $accountingClass==='OPERATING'?'selected':'' ?>>مشتريات تشغيلية (تخصم من الربح)</option>
                  <option value="CAPITAL" <?= $accountingClass==='CAPITAL'?'selected':'' ?>>شراء ممول كرأس مال</option>
                </select>
              </div>
              <div class="col-md-4 capital-field">
                <label>إسناد رأس المال</label>
                <select class="form-control" name="capital_allocation_mode" id="capitalMode">
                  <option value="ONE" <?= $capitalMode==='ONE'?'selected':'' ?>>لشريك محدد</option>
                  <option value="ALL" <?= $capitalMode==='ALL'?'selected':'' ?>>للجميع حسب الحصص</option>
                </select>
              </div>
              <div class="col-md-4 capital-field">
                <label>الشريك</label>
                <select class="form-control" name="capital_partner_id" id="capitalPartner">
                  <option value="0">اختر الشريك</option>
                  <?php foreach($capitalPartners as $partner): ?><option value="<?= (int)$partner['id'] ?>" <?= $capitalPartnerId===(int)$partner['id']?'selected':'' ?>><?= h($partner['name']) ?> (<?= number_format((float)$partner['ownership_percent'],2) ?>%)</option><?php endforeach; ?>
                </select>
              </div>
            </div>
          </div>
        </div>

        <div class="card">
          <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
            <strong>الأصناف</strong>
            <button class="btn btn-sm btn-outline-primary" type="button" id="addRow"><i class="fa fa-plus"></i> إضافة سطر</button>
          </div>
          <div class="card-body p-0">
            <div class="table-responsive">
              <table class="table table-bordered mb-0" id="itemsTable">
                <thead>
                  <tr>
                    <th>الصنف</th>
                    <th class="ua-u-w-140">الكمية</th>
                    <th class="ua-u-w-170">السعر</th>
                    <th class="ua-u-w-170">الإجمالي</th>
                    <th class="ua-u-w-72"></th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td><input class="form-control item-name" name="item_name[]" required></td>
                    <td><input class="form-control item-qty" name="qty[]" type="number" min="0.01" step="0.01" value="1" required></td>
                    <td><input class="form-control item-price" name="unit_price[]" type="number" min="0" step="0.01" value="0" required></td>
                    <td><input class="form-control item-total" value="0.00" readonly></td>
                    <td><button class="btn btn-outline-danger btn-sm w-100 remove-row" type="button"><i class="fa fa-times"></i></button></td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
          <div class="card-body">
            <div class="row">
              <div class="col-md-4">
                <label>المدفوع</label>
                <input class="form-control" name="paid" id="paid" type="number" min="0" step="0.01" value="<?= h((string)$paid) ?>">
              </div>
              <div class="col-md-4">
                <label>الإجمالي</label>
                <input class="form-control" id="grandTotal" value="0.00" readonly>
              </div>
              <div class="col-md-4">
                <label>المتبقي</label>
                <input class="form-control" id="remainingTotal" value="0.00" readonly>
              </div>
            </div>
            <div class="mt-3">
              <label>ملاحظات</label>
              <textarea class="form-control" name="notes" rows="3"><?= h($notes) ?></textarea>
            </div>
          </div>
          <div class="card-footer d-flex justify-content-end gap-2">
            <button class="btn btn-success" type="submit" name="save_purchase" value="1"><i class="fa fa-save"></i> حفظ المشتريات</button>
          </div>
        </div>
      </form>
    </div>
  </section>
</div>

<script>
(function(){
  const tbody = document.querySelector('#itemsTable tbody');
  const addBtn = document.getElementById('addRow');
  const paid = document.getElementById('paid');
  const grand = document.getElementById('grandTotal');
  const remaining = document.getElementById('remainingTotal');
  const accountingClass = document.getElementById('accountingClass');
  const capitalMode = document.getElementById('capitalMode');
  const capitalPartner = document.getElementById('capitalPartner');

  function capitalVisibility(){
    const visible = accountingClass && accountingClass.value === 'CAPITAL';
    document.querySelectorAll('.capital-field').forEach(function(el){ el.style.display = visible ? '' : 'none'; });
    if (capitalPartner) capitalPartner.disabled = !visible || (capitalMode && capitalMode.value === 'ALL');
  }

  function num(v){ const n = parseFloat(v || '0'); return Number.isFinite(n) ? n : 0; }
  function money(v){ return Math.max(0, v).toFixed(2); }

  function calc(){
    let total = 0;
    tbody.querySelectorAll('tr').forEach(function(row){
      const qty = num(row.querySelector('.item-qty')?.value);
      const price = num(row.querySelector('.item-price')?.value);
      const line = qty * price;
      const lineInput = row.querySelector('.item-total');
      if (lineInput) lineInput.value = money(line);
      total += line;
    });
    if (grand) grand.value = money(total);
    if (remaining) remaining.value = money(total - num(paid?.value));
  }

  function rebind(row){
    row.querySelectorAll('input').forEach(function(input){ input.addEventListener('input', calc); });
    const remove = row.querySelector('.remove-row');
    if (remove) {
      remove.addEventListener('click', function(){
        const rows = tbody.querySelectorAll('tr');
        if (rows.length <= 1) {
          row.querySelectorAll('input').forEach(function(input){
            input.value = input.classList.contains('item-qty') ? '1' : (input.classList.contains('item-total') ? '0.00' : '');
          });
        } else {
          row.remove();
        }
        calc();
      });
    }
  }

  if (addBtn) {
    addBtn.addEventListener('click', function(){
      const first = tbody.querySelector('tr');
      if (!first) return;
      const row = first.cloneNode(true);
      row.querySelectorAll('input').forEach(function(input){
        input.value = input.classList.contains('item-qty') ? '1' : (input.classList.contains('item-total') ? '0.00' : '');
      });
      tbody.appendChild(row);
      rebind(row);
      calc();
    });
  }

  tbody.querySelectorAll('tr').forEach(rebind);
  if (paid) paid.addEventListener('input', calc);
  if (accountingClass) accountingClass.addEventListener('change', capitalVisibility);
  if (capitalMode) capitalMode.addEventListener('change', capitalVisibility);
  capitalVisibility();
  calc();
})();
</script>
<?php include __DIR__ . '/footer.php'; ?>
