<?php
require_once __DIR__ . '/../../../core/auth.php';
require_login();
$user = current_user();
$user_id = isset($user['id']) ? (int)$user['id'] : null;


header('Content-Type: application/json');

try{
  $pdo = db();
  $payload = json_decode(file_get_contents('php://input'), true);
  
//   $data = json_decode(file_get_contents('php://input'), true);
// file_put_contents(__DIR__."/debug.log", print_r($data,true));

  if(!$payload) throw new Exception('Invalid JSON');

  if(empty($_SESSION['csrf']) || $payload['csrf'] !== $_SESSION['csrf']) throw new Exception('CSRF');

  // $user = current_user();
  // $user_id = (int)$user['id'];
  $branch_id = (int)$payload['branch_id'];
  $notes = $payload['notes'] ?? null;
  $customer_email = $payload['customer_email'] ?? null;
  $receipt_type = $payload['receipt_type'] ?? 'TakeAway';

  // إعدادات الفرع
  $st = $pdo->prepare("SELECT TaxRate FROM BranchSettings WHERE BranchID=?");
  $st->execute([$branch_id]);
  $bs = $st->fetch();
  $taxRate = $bs ? (float)$bs['TaxRate'] : 0.0;

  // عناصر الفاتورة
  $items = $payload['items'] ?? [];
  if(!$items || !is_array($items)) throw new Exception('No items');

  // جلب الأسعار الحقيقية + الأسماء (Snapshot)
  $codes = array_column($items,'code');
  $in = implode(',', array_fill(0, count($codes), '?'));
  $stmt = $pdo->prepare("SELECT Code, IName, PriceTW FROM Items WHERE Code IN ($in)");
  $stmt->execute($codes);
  $map = [];
  foreach($stmt->fetchAll() as $r){ $map[$r['Code']] = $r; }

  $detailRows = [];
  $subTotal = 0.0;
  foreach($items as $it){
    $code = (int)$it['code'];
    $qty = max(1, (float)$it['qty']);
    if(!isset($map[$code])) throw new Exception('Item not found: '.$code);
    $price = (float)$map[$code]['PriceTW'];
    $name  = $map[$code]['IName'];
    $value = $qty * $price;
    $subTotal += $value;
    $detailRows[] = ['code'=>$code,'name'=>$name,'qty'=>$qty,'price'=>$price,'value'=>$value];
  }

  // خصم
  $dtype = $payload['discount_type'] ?? 'amount';
  $dval  = (float)($payload['discount_value'] ?? 0);
  $discountAmt = 0.0;
  if($dtype==='percent'){ $discountAmt = min($subTotal, $subTotal * ($dval/100)); }
  else { $discountAmt = min($subTotal, $dval); }

  $taxable = max(0, $subTotal - $discountAmt);
  $tax = round($taxable * ($taxRate/100), 2);
  $total = round($taxable + $tax, 2);

  // دفعات
  $payCash = (float)($payload['pay_cash'] ?? 0);
  $payCard = (float)($payload['pay_card'] ?? 0);
  $amountReceived = (float)($payload['amount_received'] ?? 0);
  $paid = round($payCash + $payCard, 2);
  $changeDue = max(0, $amountReceived - min($amountReceived, max(0, $total - $payCard)));
  $status = ($paid >= $total) ? 'Paid' : (($paid > 0) ? 'Partial' : 'Unpaid');

  $pdo->beginTransaction();

 // إدخال رأس الفاتورة
$ins = $pdo->prepare("
INSERT INTO salesreceipt
(ReceiptDate, ReceiptType, BranchID, CustomerID, DeliveryAddress, CaptainID, TableNo, DriverID,
 SubTotal, Discount, DiscountPercent, Tax, Total, Notes, UserID, CashierShiftID, PaidAmount, ChangeDue, PaymentStatus, CustomerEmail)
VALUES (NOW(),?,?,?,?, ?,?,?, ?,?,?, ?,?,?, ?,?,?, ?,?,?)
");

$ins->execute([
$receipt_type,
$branch_id,
null, // CustomerID
null, // DeliveryAddress
null, // CaptainID
null, // TableNo
null, // DriverID
$subTotal,
$discountAmt,
($dtype === 'percent' ? $dval : null), // DiscountPercent
$tax,
$total,
$notes,
$user_id,   // ← هنا هيبقى null لو مفيش مستخدم
null,       // CashierShiftID
$paid,
$changeDue,
$status,
$customer_email
]);

$rid = (int)$pdo->lastInsertId();


  // تفاصيل
  $insd = $pdo->prepare("
    INSERT INTO SalesReceiptDetails (ReceiptID, ItemID, ItemName, Qty, Price, Value, Notes)
    VALUES (?,?,?,?,?,?,NULL)
  ");
  foreach($detailRows as $dr){
    $insd->execute([$rid, $dr['code'], $dr['name'], $dr['qty'], $dr['price'], $dr['value']]);
  }

  // المدفوعات
  if($payCash > 0){
    $pdo->prepare("INSERT INTO SalesPayments (ReceiptID, Method, Amount) VALUES (?,?,?)")
        ->execute([$rid, 'Cash', $payCash]);
  }
  if($payCard > 0){
    $pdo->prepare("INSERT INTO SalesPayments (ReceiptID, Method, Amount) VALUES (?,?,?)")
        ->execute([$rid, 'Card', $payCard]);
  }

  $pdo->commit();

  // إرسال PDF وإيميل (اختياري)
  if($customer_email){
    // مجرد نداء بسيط، تقدر تغيّره إلى Queue
    @file_get_contents(__DIR__ . "/../receipt/send_email.php?id=".$rid);
  }

  echo json_encode(['success'=>true,'receipt_id'=>$rid]);

}catch(Exception $e){
  if(isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
  http_response_code(400);
  echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}
