<?php
$page_title = 'فاتورة مبيعات جديدة';
require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/shop_lib.php';

require_login();
$conn = ensure_db(true);
if(function_exists('require_perm')) require_perm('can_manage_sales');

ensure_shop_tables($conn);

$products = $conn->query("SELECT id,name,price FROM shop_products ORDER BY name ASC");

$err = '';
if(isset($_POST['create'])){
  $cname  = $conn->real_escape_string($_POST['customer_name'] ?? '');
  $cphone = $conn->real_escape_string($_POST['customer_phone'] ?? '');
  $items  = $_POST['item'] ?? [];
  $total  = 0;
  $clean  = [];

  foreach($items as $it){
    $pid = (int)($it['pid'] ?? 0);
    $qty = (int)($it['qty'] ?? 0);
    if($pid<=0 || $qty<=0) continue;
    $pr = $conn->query("SELECT name,price FROM shop_products WHERE id=$pid LIMIT 1");
    if(!$pr || !$pr->num_rows) continue;
    $p = $pr->fetch_assoc();
    $price = (float)$p['price'];
    $lt = $price*$qty;
    $total += $lt;
    $clean[] = ['pid'=>$pid,'name'=>$p['name'],'qty'=>$qty,'price'=>$price,'lt'=>$lt];
  }

  if(!$clean){
    $err = 'اختر منتج واحد على الأقل';
  } else {
    $payload = [
      'customer_name' => $_POST['customer_name'] ?? '',
      'customer_phone' => $_POST['customer_phone'] ?? '',
      'discount' => 0,
      'notes' => '',
      'created_by' => (int)($_SESSION['admin_id'] ?? 0),
      'items' => []
    ];
    foreach($clean as $c){
      $payload['items'][] = [
        'product_id' => (int)$c['pid'],
        'name' => $c['name'],
        'qty' => (int)$c['qty'],
        'price' => (float)$c['price'],
      ];
    }
    $sid = shop_create_sale($conn, $payload);
    header('Location: sales_view.php?id='.$sid);
    exit;
  }
}

$active_tab = 'new';
$UA_FORCE_DESIGN_V2 = true;
$uaAndroidSalesNew = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidSalesNew) $UA_PAGE_CSS = ['assets/css/android_sales_new.css'];
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';

if ($uaAndroidSalesNew) {
  require __DIR__ . '/android_sales_new.php';
  include __DIR__ . '/footer.php';
  return;
}

?>
<div class="content-wrapper ua-extracted-page">
  <section class="content-header"><div class="container-fluid"><h1 class="mb-0">فاتورة مبيعات جديدة</h1></div></section>
  <section class="content"><div class="container-fluid">
    <?php if($err){?><div class="alert alert-danger"><?=h($err)?></div><?php }?>
    <div class="card"><div class="card-body">
      <form method="post">
        <div class="row">
          <div class="col-md-6"><label>اسم العميل</label><input name="customer_name" class="form-control"></div>
          <div class="col-md-6"><label>هاتف العميل</label><input name="customer_phone" class="form-control"></div>
        </div>
        <hr>
        <h5 class="mb-3">العناصر</h5>

        <div class="table-responsive">
          <table class="table table-bordered align-middle" id="itemsTable">
            <thead>
              <tr>
                <th class="ua-u-w-40p">المادة</th>
                <th class="ua-u-w-15p">الكمية</th>
                <th class="ua-u-w-15p">السعر الإفرادي</th>
                <th class="ua-u-w-15p">الإجمالي</th>
                <th class="ua-u-w-15p">حذف</th>
              </tr>
            </thead>
            <tbody id="items">
              <tr class="item-row">
                <td>
                  <select class="form-control product" name="item[0][pid]" onchange="calc()">
                    <option value="0" data-price="0">اختر مادة</option>
                    <?php
                      // نحتاج إعادة تنفيذ الاستعلام لأن while أعلاه يستهلكه
                      $products2 = $conn->query("SELECT id,name,price FROM shop_products ORDER BY name ASC");
                      while($p=$products2->fetch_assoc()){
                        $pid = (int)$p['id'];
                        $pname = h($p['name']);
                        $pprice = (float)$p['price'];
                        echo "<option value=\"$pid\" data-price=\"".number_format($pprice,2,'.','')."\">$pname</option>";
                      }
                    ?>
                  </select>
                </td>
                <td><input class="form-control qty" name="item[0][qty]" type="number" value="1" min="1" oninput="calc()"></td>
                <td><input class="form-control unit" type="text" value="0.00" readonly></td>
                <td><input class="form-control line" type="text" value="0.00" readonly></td>
                <td><button type="button" class="btn btn-outline-danger w-100" onclick="removeRow(this)"><i class="fa fa-times"></i></button></td>
              </tr>
            </tbody>
          </table>
        </div>

        <div class="d-flex justify-content-between align-items-center">
          <button type="button" class="btn btn-outline-secondary" onclick="addRow()"><i class="fa fa-plus"></i> إضافة سطر</button>
          <div class="ua-u-minw-260">
            <div class="input-group">
              <div class="input-group-prepend"><span class="input-group-text">الإجمالي</span></div>
              <input class="form-control" id="grandTotal" value="0.00" readonly>
            </div>
          </div>
        </div>

        <div class="mt-3">
          <button class="btn btn-success" name="create"><i class="fa fa-save"></i> إنشاء الفاتورة</button>
        </div>
      </form>
    </div></div>
  </div></section>
</div>
<script>
let idx=1;

function reindex(){
  const rows = document.querySelectorAll('#items .item-row');
  rows.forEach((r,i)=>{
    const sel = r.querySelector('select.product');
    const qty = r.querySelector('input.qty');
    if(sel) sel.name = `item[${i}][pid]`;
    if(qty) qty.name = `item[${i}][qty]`;
  });
  idx = rows.length;
}

function addRow(){
  const tpl = document.querySelector('#items .item-row');
  const clone = tpl.cloneNode(true);
  // reset
  clone.querySelector('select.product').value = '0';
  clone.querySelector('input.qty').value = 1;
  clone.querySelector('input.unit').value = '0.00';
  clone.querySelector('input.line').value = '0.00';
  document.getElementById('items').appendChild(clone);
  reindex();
  calc();
}

function removeRow(btn){
  const rows = document.querySelectorAll('#items .item-row');
  if(rows.length<=1){
    btn.closest('.item-row').querySelector('select.product').value='0';
    btn.closest('.item-row').querySelector('input.qty').value=1;
  } else {
    btn.closest('.item-row').remove();
  }
  reindex();
  calc();
}

function calc(){
  let total = 0;
  document.querySelectorAll('#items .item-row').forEach(r=>{
    const opt = r.querySelector('select.product').selectedOptions[0];
    const price = parseFloat(opt?.dataset.price || '0');
    const qty = parseInt(r.querySelector('input.qty').value || '0',10) || 0;
    const line = price * qty;
    r.querySelector('input.unit').value = price.toFixed(2);
    r.querySelector('input.line').value = line.toFixed(2);
    total += line;
  });
  document.getElementById('grandTotal').value = total.toFixed(2);
}

document.addEventListener('DOMContentLoaded', calc);
</script>
<?php include __DIR__ . '/footer.php'; ?>
