=== RETURN EVENT AND ACCOUNTING LISTENER ===

====================================================================================================
FILE=app/Events/ReturnCreated.php
====================================================================================================
<?php

namespace App\Events;

use App\ReturnProduct;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class ReturnCreated
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public $order,$productStore;
    public function __construct(ReturnProduct $order,$productStores=[])
    {
        $this->order = $order;
        $this->productStores = $productStores;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}


====================================================================================================
FILE=app/Listeners/UpdateProductQuantityReturn.php
====================================================================================================
FILE_FOUND=YES

--- METHOD=handle ---
    public function handle($event)
    {
        try {

            $order = $event->order;
            $productStores = $event->productStores;
            $details = $order->details()->get();
            foreach ($details as $item){
                if($item->is_service==1)continue;
                $productStore = isset($productStores[$item->id.$item->pivot->store_id])
                    ?$productStores[$item->id.$item->pivot->store_id]
                    :ProductStore::where('product_id', $item->id)
                        ->where('store_id', $item->pivot->store_id)
                        ->first();
                $orderQty  = $item->pivot->qty;
                $prodstorUnit = $productStore->unit_id;
                $produtUnits =  ProductUnit::where('product_id', $item->id)->get();
                $orderUnit = $produtUnits->where('unit_id', $item->pivot->unit_id)->first();
                $storUnit  = $produtUnits->where('unit_id', $prodstorUnit)->first();

                if ($prodstorUnit != $item->pivot->unit_id) {
                    if ($storUnit->pieces_num < $orderUnit->pieces_num) {
                        $a = $orderUnit->pieces_num/$storUnit->pieces_num;
                        $orderQty = $orderQty*$a;
                    } else {
                        $a = $orderUnit->pieces_num/$storUnit->pieces_num;
                        if($a<1){
                            $orderQty = $orderQty*$a;
                        }else{
                            $orderQty = $orderQty/$a;
                        }
                    }
                }
                if($order->return_type=='sales'){
                    $productStore->sale_count -= $orderQty;
                }else{
                    $oldCost = $storUnit->cost_price;
                    $oldQty = ($productStore->qty-$productStore->sale_count)?:1;
                    $newQty = $orderQty;
                    $newCost = $item->pivot->price;
                    //$totalNew = ($newQty*$newCost)/$oldQty;
                    //$newAvg = $oldCost-$totalNew;
                    $totalqty = $oldQty-$newQty;
                    if($totalqty) {
                        $productCost = $newCost;
                        if(Setting::findByKey('productCost')=='avg') {
                            $newAvg = (($oldCost * $oldQty) - ($newQty * $newCost)) / ($oldQty - $newQty);
                            $productCost = $newAvg;
                        }
                        $productCost = round($productCost, 2);
                        $item->last_cost = $storUnit->cost_price;
                        $storUnit->cost_price = $productCost;
                        $storUnit->save();
                        $item->avg_cost = round($productCost, 2);
                        $item->save();
                    }
                    $productStore->qty -= $orderQty;
                }

                $productStore->save();

            }
            /*
             * Sales returns must follow the financial treatment of the
             * original invoice. Never trust request('bank_id') or a mobile
             * is_cash value when an original invoice is linked.
             *
             * cash          => original invoice treasury
             * visa          => original invoice bank
             * link transfer => original invoice bank (تحويل بنكي)
             * delayed       => reduce client receivable
             */
            if ($order->return_type == 'sales') {
                $originalOrder = $order->order;

                $paymentType = $originalOrder
                    ? strtolower(trim((string) $originalOrder->payment_type))
                    : null;

                $isCreditReturn =
                    ($originalOrder && $paymentType == 'delayed')
                    || (!$originalOrder && !$order->is_cash);

                if ($isCreditReturn) {
                    $order->client
                        ->transactions()
                        ->create([
                            'value' => -$order->return_value,
                            'note' => ' خصم قيمة مرتجعات من الحساب ',
                            'transaction_type' => $order->return_type,
                            'record_id' => $order->id
                        ]);
                } else {
                    if ($originalOrder) {
                        $bankPaymentTypes = [
                            'cash',
                            'visa',
                            'link transfer',
                        ];

                        if (!in_array(
                            $paymentType,
                            $bankPaymentTypes,
                            true
                        )) {
                            throw new \Exception(
                                'طريقة دفع الفاتورة الأصلية غير مدعومة للمرتجع: '
                                . $originalOrder->payment_type
                            );
                        }

                        $bankId = (int) $originalOrder->bank_id;
                    } else {
                        /*
                         * Backward-compatible fallback for old unlinked
                         * returns created from the web interface.
                         */
                        $bankId = (int) request('bank_id');
                    }

                    if (!$bankId) {
                        throw new \Exception(
                            'تعذر تحديد حساب رد قيمة المرتجع'
                        );
                    }

                    $bank = Bank::find($bankId);

                    if (!$bank) {
                        throw new \Exception(
                            'الحساب المالي المرتبط بالفاتورة الأصلية غير موجود'
                        );
                    }

                    $grand = currency(
                        $order->return_value,
                        currency()->getUserCurrency(),
                        $bank->currency,
                        false
                    );

                    $grand = round((float) $grand, 2);

                    $trans = [
                        'bank_id' => $bank->id,
                        'op_date' => date('Y-m-d'),
                        'total' => $bank->balance,
                        'due' => (float) $bank->balance - $grand,
                        'type' => '1',
                        'note' => 'مرتجع مبيعات  | ' . $order->client->name,
                        'value' => $grand,
                    ];

                    $bank->balance =
                        (float) $bank->balance - $grand;

                    $bank->save();

                    if ($order->transaction) {
                        $order->transaction()->update($trans);
                    } else {
                        $order->transaction()->create($trans);
                    }
                }
            } elseif ($order->is_cash) {
                /*
                 * Purchase return behavior is preserved unchanged.
                 */
                $bankId = request('bank_id');

                if ($bankId) {
                    $banktans = $order->transaction()->first();

                    if ($banktans) {
                        $bank = $banktans->bank;
                    } else {
                        $bank = Bank::find($bankId);
                    }

                    $trans["bank_id"] = $bankId;
                    $bank = Bank::find($bankId);
                    $trans["op_date"] = date('Y-m-d');
                    $trans["total"] = $bank->balance;

                    $grand = currency(
                        $order->return_value,
                        currency()->getUserCurrency(),
                        $bank->currency,
                        false
                    );

                    $note = 'مرتجع مشتريات  | ' . $order->client->name;
                    $trans["due"] = $bank->balance + $grand;
                    $bank->balance += $grand;
                    $trans["type"] = "2";
                    $trans["note"] = $note;
                    $trans["value"] = $grand;
                    $bank->save();

                    if ($order->transaction) {
                        $order->transaction()->update($trans);
                    } else {
                        $order->transaction()->create($trans);
                    }
                }
            } else {
                $order->client
                    ->transactions()
                    ->create([
                        'value' => -$order->return_value,
                        'note' => ' خصم قيمة مرتجعات من الحساب ',
                        'transaction_type' => $order->return_type,
                        'record_id' => $order->id
                    ]);
            }
        } catch (\Exception $exception) {
            \Log::error($exception->getMessage());

            throw $exception;
        }

    }

=== RETURN MODELS ===

====================================================================================================
FILE=app/ReturnDetail.php
====================================================================================================
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ReturnDetail extends Model
{
    protected $table = 'return_detailes';

    protected $fillable = [
        'return_id','store_name','unit_name','product_name',
        'store_id','unit_id', 'qty','cost','price',
        'cost_egp','price_egp','product_id'
    ];
    public function returns(){
        return $this->belongsTo(ReturnProduct::class,'return_id','id');
    }
    public function product(){
        return $this->belongsTo(Product::class,'product_id','id')->withTrashed();
    }
}


====================================================================================================
FILE=app/ReturnProduct.php
====================================================================================================
<?php

namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Kyslik\ColumnSortable\Sortable;

class ReturnProduct extends Model
{
    use SoftDeletes;
    protected $table = 'returns';
    protected $fillable = [
        'client_id','return_type','return_value','is_cash','return_date','currency','sales_value','sales_value_egp',
        'sale_id','discount','discount_type','total','manager_id','order_id','creator_id','tax','tax_value',
        // TESTMOBILE_FULL_SALES_RETURN_SCHEMA_20260721
        'return_mode',
        'is_immutable',
        'original_payment_type',
        'original_bank_id',
        'original_invoice_uuid',
        'price_includes_tax',
        'zatca_invoice_uuid',
        'zatca_qr_payload',
        'zatca_signed_xml',
        'zatca_reporting_status',
        'zatca_validation_status',
        'zatca_invoice_hash',
        'zatca_raw_response',
        'zatca_submitted_at',
    ];

    protected $casts = [
        'zatca_raw_response' => 'array',
        'zatca_submitted_at' => 'datetime',
        'is_immutable' => 'boolean',
        'price_includes_tax' => 'boolean',
        'original_bank_id' => 'integer',
    ];

    public function gettaxValueAttribute(){
        $tax =  $this->tax/100;
        $total = $this->total;
        $taxplusone = 1+ $tax;
        $orignalValue = $total / $taxplusone;
        $taxvalue =$orignalValue * $tax;
        return $taxvalue;
    }
    public function gettaxValueCaluclatedAttribute(){
        $tax =  $this->tax/100;
        $total = $this->total;
        $taxplusone = 1+ $tax;
        $orignalValue = $total / $taxplusone;
        $taxvalue =$orignalValue * $tax;
        return $taxvalue;
    }
    public function transaction(){
        return $this->morphOne(BankTransaction::class,'transactionable');
    }
    public function details(){
        return $this->belongsToMany(Product::class,'return_detailes','return_id','product_id')
            ->withPivot([
                'store_name',
                'unit_name',
                'product_name',
                'store_id',
                'unit_id',
                'qty',
                'cost',
                'price',
                'created_at',
                // TESTMOBILE_FULL_SALES_RETURN_SCHEMA_20260721
                'order_detail_id',
                'is_service',
                'unit_net_amount',
                'gross_line_total',
                'discount_amount',
                'discount_inclusive_amount',
                'line_net_amount',
                'tax_percent',
                'tax_amount',
                'total_including_tax',
            ])
            ->withTimestamps()->withTrashed();

    }
    public function creator(){
        return $this->belongsTo(User::class,'creator_id','id');
    }
    public function client(){
        return $this->belongsTo(Person::class,'client_id','id');
    }
    public function order(){
        return $this->belongsTo(Order::class,'order_id','id')->withTrashed();
    }
    public function saleMan(){
        return $this->belongsTo(Employee::class,'sale_id','id');
    }

    /*
     * FORCE_NEW_RETURN_CURRENCY_TO_SAR
     * This Saudi/ZATCA installation creates records in SAR only.
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->currency = 'SAR';
        });
    }

}


=== ORDER MODEL RELATIONS ===

====================================================================================================
FILE=app/Order.php
====================================================================================================
FILE_FOUND=YES

--- METHOD=items ---
    public function items()
    {
        return $this->hasMany(OrderDetail::class, 'order_id', 'id');
    }

--- METHOD=details ---
    public function details()
    {
        return $this->belongsToMany(Product::class, 'order_detailes', 'order_id', 'product_id')
            ->withPivot([
                'store_name',
                'unit_name',
                'product_name',
                'store_id',
                'unit_id',
                'qty',
                'bounse',
                'bounse_unit_id',
                'bounseUnitText',
                'is_service',
                'return_qty',
                'cost',
                'price',
                'total',
                'created_at',
                'markter',
                'customer_price',
                'status',
                'comment',
                'discount1',
                'discount2',
                'serive_datetime',
                'employee_id',
                'employee_name'
            ])
            ->withTimestamps();
    }

--- METHOD=returns ---
METHOD_FOUND=NO

--- METHOD=transaction ---
public function transaction()
    {
        return $this->morphOne(BankTransaction::class, 'transactionable');
    }

--- METHOD=client ---
    public function client()
    {
        return $this->belongsTo(Person::class, 'client_id', 'id')->withTrashed();
    }

=== BANK RESOLUTION ===

====================================================================================================
FILE=app/Bank.php
====================================================================================================
FILE_FOUND=YES

--- METHOD=resolveForPayment ---
METHOD_FOUND=NO

=== CURRENT RETURN CONTROLLER ENTRY POINTS ===

====================================================================================================
FILE=app/Http/Controllers/ReturnsController.php
====================================================================================================
FILE_FOUND=YES

--- METHOD=createSales ---
    public function createSales(){
        return $this->create('sales');
    }

--- METHOD=createPurchase ---
    public function createPurchase(){
        return $this->create('purchase');
    }

--- METHOD=store ---
	public function store(Request $request) {

	    try {
            DB::beginTransaction();
            $inputs = $request->except('_token');
            $inputs['order']['creator_id'] = auth()->user()->id;
            $inputs['order']['is_cash'] = $request->has('is_cash');
            $inputs['order']['discount_type'] = isset($inputs['order']['discount_type'])?2:1;
            $inputs['order']['sales_value_egp'] = currency($inputs['order']['sales_value'],currency()->getUserCurrency(),currency()->config('default'), $format = false);
            $order = null;
            if($inputs['order']['order_id']){
                $order = Order::find($inputs['order']['order_id']);
            }
            $client = $inputs['order']['client_id'];
            foreach ($inputs['product'] as $pid=>$prod){
                $totalReturn = ReturnDetail::join('returns',function($qry)use($client){
                    $qry->on('returns.id','=','return_id');
                    $qry->where('client_id',$client);
                    $qry->whereNull('deleted_at');
                })->where('product_id',$pid)->sum('qty');
                $settings = Setting::get()->pluck('value','key')->toArray();
                if(isset($settings['show_all_products_returns']) && $settings['show_all_products_returns']==1) {
                    $totalOrder = OrderDetail::join('orders', function ($qry) use ($client) {
                        $qry->on('orders.id', '=', 'order_id');
                        $qry->where('client_id', $client);
                    })->where('product_id', $pid)->sum(DB::raw('qty'));
                    //dd($totalReturn,$totalOrder,$prod['qty']);
                    $totalReturn += $prod['qty'];
                    if ($totalReturn > $totalOrder) {
                        throw new \Exception('المرتجعات أكبر من المبيعات لهذا الصنف  ' . $prod['product_name']);
                    }
                }
                if($order){
                    $details = OrderDetail::where('order_id',$order->id)
                        ->where('product_id',$pid)
                        ->first();
                    if($details->unit_id==$prod['unit_id']){
                        $details->return_qty += $prod['qty'];
                        $details->save();
                    }
                }
            }

            $return = ReturnProduct::create($inputs['order']);
            if($return->return_type=='sales'){
                $logNote = "فاتورة مرتجع مبيعات رقم ".$return->id." للعميل ".$return->client->name." بقيمة ".$return->return_value;
            }else{
                $logNote = "فاتورة مرتجع مشتريات رقم ".$return->id." من المورد ".$return->client->name." بقيمة ".$return->return_value;
            }
            /*activity()
                ->performedOn($return)
                ->log($logNote);*/
            if(isset($inputs['product'])){
                foreach ($inputs['product'] as $key=>$value){
                    //$inputs['product'][$key]['cost'] = currency($inputs['product'][$key]['cost'],"SAR",$return->currency, false);
                    if($inputs['product'][$key]['cost'] > $inputs['product'][$key]['price']){
                        $inputs['product'][$key]['cost'] = $inputs['product'][$key]['price'];
                    }
                    $inputs['product'][$key]['cost_egp'] = currency($value['cost'],currency()->getUserCurrency(),currency()->config('default'), $format = false);
                    $inputs['product'][$key]['price_egp'] = currency($value['price'],currency()->getUserCurrency(),currency()->config('default'), $format = false);
                }
            }
            $return->details()->attach($inputs['product']);

            event(new ReturnCreated($return));
            if($order){
                $this->setOrderProfit($order,$inputs['order']['return_value']);
            }
            DB::commit();
            if($return->return_type=='sales'){
                $route = route('ordersReturn.index');
            }else{
                $route = route('purchasesReturn.index');
            }
            $request->session()->flash('alert-success', 'تم إضافة المرتجع بنجاح');
            //return redirect(route('returns.getPrint',$return->id));
            return redirect($route);
		} catch (\Exception $e) {
			DB::rollback();
            $request->session()->flash('alert-danger', ' حدث خطأ اثناء اضافة المرتجع '.$e->getMessage());
			//dd($e->getMessage());
		}
        return back();
	}

--- METHOD=setOrderProfit ---
    public function setOrderProfit($order,$return_value){
        // $order->total = $order->fgrand_order_total;
        // $order->total_return += $return_value;
        // $order->discount_value = $order->dicount_value;
        // $total = $order->total - $order->discount_value;
        // $total = $total>0?$total:0;
        // if($total==0) {
        //     $order->discount = 0;
        //     $order->discount_value = 0;
        // }
        // if($order->paid>=$total){
        //     $order->paid = $total;
        // }
        // $order->due = $total - $order->paid;
        $order->profit = $order->order_profit;
        $order->save();
    }

=== CURRENT MOBILE RETURN CREATION ===

====================================================================================================
FILE=app/Services/Mobile/CreateSalesReturnService.php
====================================================================================================
FILE_FOUND=YES

--- METHOD=handle ---
    public function handle(array $payload)
    {
        $user = Auth::user();
        if (!$user) {
            throw new \Exception('غير مصرح');
        }

        $settings = Setting::query()->pluck('value', 'key')->toArray();
        $priceIncludesTax = $settings['PriceIncludesTax'] ?? 'no';
        $taxPercent = isset($payload['tax'])
            ? (float) $payload['tax']
            : (float) ($settings['taxValue'] ?? 15);
        $roundingUp = isset($settings['rounding_up']) && (string) $settings['rounding_up'] === '1';

        $clientId = (int) ($payload['client_id'] ?? 0);
        $client = Person::find($clientId);
        if (!$client) {
            throw new \Exception('العميل غير موجود');
        }

        $order = null;
        if (!empty($payload['order_id'])) {
            $order = Order::find($payload['order_id']);
            if (!$order) {
                throw new \Exception('الفاتورة الأصلية غير موجودة');
            }
        }

        $items = isset($payload['items']) && is_array($payload['items']) ? $payload['items'] : [];
        if (count($items) === 0) {
            throw new \Exception('يجب إضافة أصناف للمرتجع');
        }

        $attach = [];
        $itemsSubtotal = 0.0;

        /*
         * MOBILE_SERVICE_RETURN_NO_STOCK
         *
         * return_qty updates are collected here and executed only inside
         * the database transaction after all rows pass validation.
         */
        $orderDetailAdjustments = [];

        foreach ($items as $row) {
            $productId = (int) ($row['product_id'] ?? 0);
            $product = Product::with(['productUnit', 'productStore'])->find($productId);
            if (!$product) {
                throw new \Exception('صنف غير موجود');
            }

            $qty = (float) ($row['qty'] ?? 0);
            if ($qty <= 0) {
                throw new \Exception('كمية مرتجع غير صحيحة لـ ' . $product->name);
            }

            // Cap returns vs sold qty when setting requires it (same as web)
            if (isset($settings['show_all_products_returns']) && (string) $settings['show_all_products_returns'] === '1') {
                $totalReturn = ReturnDetail::join('returns', function ($qry) use ($clientId) {
                    $qry->on('returns.id', '=', 'return_id');
                    $qry->where('client_id', $clientId);
                    $qry->whereNull('deleted_at');
                })->where('product_id', $productId)->sum('qty');

                $totalOrder = OrderDetail::join('orders', function ($qry) use ($clientId) {
                    $qry->on('orders.id', '=', 'order_id');
                    $qry->where('client_id', $clientId);
                })->where('product_id', $productId)->sum(DB::raw('qty'));

                if (($totalReturn + $qty) > $totalOrder) {
                    throw new \Exception('المرتجعات أكبر من المبيعات لهذا الصنف ' . $product->name);
                }
            }

            $isService = !empty($product->is_service);

            if ($isService) {
                /*
                 * A service has no product_unit or product_store balance.
                 * IDs 1 are reference values only and never cause stock
                 * movement because ReturnCreated skips service products.
                 */
                $unit = \App\Unit::find(1);
                $store = \App\Store::find(1);

                if (!$unit) {
                    throw new \Exception(
                        'الوحدة الافتراضية رقم 1 غير موجودة'
                    );
                }

                if (!$store) {
                    throw new \Exception(
                        'المخزن الافتراضي رقم 1 غير موجود'
                    );
                }

                $unitId = 1;
                $unitName = 'خدمة';
                $storeId = 1;
                $storeName = $store->name;

                $price = array_key_exists('price', $row)
                    ? (float) $row['price']
                    : (float) ($product->last_cost ?? 0);

                // Services never carry inventory cost.
                $cost = 0.0;
            } else {
                $unitId = isset($row['unit_id'])
                    ? (int) $row['unit_id']
                    : null;

                $unit = $unitId
                    ? $product->productUnit
                        ->firstWhere('id', $unitId)
                    : $product->productUnit->first();

                if (!$unit) {
                    throw new \Exception(
                        'لا توجد وحدة للصنف ' . $product->name
                    );
                }

                $storeId = isset($row['store_id'])
                    ? (int) $row['store_id']
                    : (int) optional(
                        $product->productStore->first()
                    )->store_id;

                if (!$storeId) {
                    throw new \Exception(
                        'لا يوجد مخزن للصنف ' . $product->name
                    );
                }

                $unitId = (int) $unit->id;
                $unitName = $unit->name;
                $storeName = $row['store_name']
                    ?? optional(
                        \App\Store::find($storeId)
                    )->name;

                $price = array_key_exists('price', $row)
                    ? (float) $row['price']
                    : (float) (
                        $unit->pivot->sale_price ?? 0
                    );

                $cost = array_key_exists('cost', $row)
                    ? (float) $row['cost']
                    : (float) (
                        $unit->pivot->cost_price ?? 0
                    );

                if ($cost > $price) {
                    $cost = $price;
                }
            }

            $lineTotal = round($qty * $price, 2);
            $itemsSubtotal += $lineTotal;

            if ($order) {
                $details = OrderDetail::where(
                    'order_id',
                    $order->id
                )
                    ->where(
                        'product_id',
                        $productId
                    )
                    ->first();

                if (
                    $details
                    && (int) $details->unit_id ===
                        (int) $unitId
                ) {
                    if (
                        !isset(
                            $orderDetailAdjustments[
                                $details->id
                            ]
                        )
                    ) {
                        $orderDetailAdjustments[
                            $details->id
                        ] = 0.0;
                    }

                    $orderDetailAdjustments[
                        $details->id
                    ] += $qty;
                }
            }

            $attach[$productId] = [
                'store_id' => $storeId,
                'unit_id' => $unitId,
                'store_name' => $storeName,
                'unit_name' => $unitName,
                'product_name' => $product->name,
                'qty' => $qty,
                'cost' => $cost,
                'price' => $price,
                'cost_egp' => $cost,
                'price_egp' => $price,
            ];
        }

        $discount = (float) ($payload['discount'] ?? 0);
        $discountType = (int) ($payload['discount_type'] ?? 1);
        if ($discountType !== 2) {
            $discountType = 1;
        }

        $totals = $this->calculator->calculate(
            $itemsSubtotal,
            $discount,
            $discountType,
            $taxPercent,
            $priceIncludesTax,
            $roundingUp
        );

        DB::beginTransaction();

        try {
            foreach (
                $orderDetailAdjustments
                as $detailId => $adjustmentQty
            ) {
                $detail = OrderDetail::find($detailId);

                if (!$detail) {
                    throw new \Exception(
                        'تعذر العثور على سطر الفاتورة الأصلية'
                    );
                }

                $detail->return_qty =
                    (float) $detail->return_qty
                    + (float) $adjustmentQty;

                $detail->save();
            }

            $returnData = [
                'client_id' => $client->id,
                'return_type' => 'sales',
                'creator_id' => $user->id,
                'order_id' => $order ? $order->id : null,
                'return_date' => $payload['return_date'] ?? date('Y-m-d'),
                'currency' => 'SAR',
                'tax' => $taxPercent,
                'tax_value' => $totals['tax_value_stored'],
                'discount' => $discount,
                'discount_type' => $discountType,
                'sales_value' => $totals['items_subtotal'],
                'sales_value_egp' => $totals['items_subtotal'],
                'return_value' => $totals['total'],
                'total' => $totals['total'],
                /*
                 * The financial treatment of a linked sales return must
                 * follow the original invoice, not a client-supplied flag.
                 *
                 * cash / visa / bank transfer => refund from original bank
                 * delayed                     => reduce client receivable
                 */
                'is_cash' => $order && in_array(
                    strtolower(trim((string) $order->payment_type)),
                    ['cash', 'visa', 'link transfer'],
                    true
                ) ? 1 : 0,
            ];

            $return = ReturnProduct::create($returnData);
            $return->details()->attach($attach);

            event(new ReturnCreated($return));

            if ($order) {
                $order->total_return = (float) $order->total_return + (float) $totals['total'];
                $order->save();
            }

            DB::commit();

            return $return->fresh(['details', 'client', 'order']);
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }

=== DATABASE ACCOUNTING SNAPSHOT ===

--- BANKS ---
ROW_COUNT=2
id=1 | name=الخزنة | balance=609.45 | currency=SAR | type=2 | percent=0.0
id=2 | name=بنك الراجحي | balance=488.08 | currency=SAR | type=1 | percent=0.0

--- ORDER_341 ---
ROW_COUNT=1
id=341 | invoice_number=341 | client_id=1 | payment_type=visa | bank_id=2 | total=10.0 | paid=10.0 | due=0.0 | total_return=10.0 | zatca_reporting_status=CLEARED | zatca_validation_status=PASS

--- RETURN_4 ---
ROW_COUNT=1
id=4 | order_id=341 | client_id=1 | return_type=sales | return_value=10 | total=10.0 | is_cash=1 | return_mode=None | is_immutable=0 | original_payment_type=None | original_bank_id=None | zatca_reporting_status=CLEARED | zatca_validation_status=PASS

--- RETURN_4_LINES ---
ROW_COUNT=1
id=1 | return_id=4 | product_id=3 | order_detail_id=None | qty=1 | price=10.0 | is_service=0 | discount_amount=0.0 | tax_amount=0.0 | total_including_tax=0.0

--- RETURN_4_BANK_TRANSACTIONS ---
ROW_COUNT=0

--- RETURN_4_CLIENT_TRANSACTIONS ---
ROW_COUNT=0

=== SCHEMA INDEXES ===

TABLE=returns
INDEX=returns_order_full_mode_unique UNIQUE=1

TABLE=return_detailes
INDEX=return_detailes_order_detail_unique UNIQUE=1

=== SAFETY ===
DATABASE_INTEGRITY=ok
FOREIGN_KEY_ERRORS=0
FILES_CHANGED=NO
DATABASE_CHANGED=NO
ZATCA_REQUEST_SENT=NO