<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\Services\AccountingService; 

class PurchaseReturnController extends Controller
{
    /**
     * 1. GET SEMUA RIWAYAT RETUR PEMBELIAN
     */
    public function index(Request $request)
    {
        $user = $request->user();
        $branchId = ($user && $user->role !== 'owner') ? $user->branch_id : null;

        $returns = DB::table('purchase_returns')
            ->join('purchases', 'purchase_returns.purchase_id', '=', 'purchases.id')
            ->join('suppliers', 'purchase_returns.supplier_id', '=', 'suppliers.id')
            ->join('branches', 'purchase_returns.branch_id', '=', 'branches.id')
            ->join('users', 'purchase_returns.user_id', '=', 'users.id')
            ->leftJoin('accounts', 'purchase_returns.refund_account_id', '=', 'accounts.id')
            ->when($branchId, function ($query, $branchId) {
                return $query->where('purchase_returns.branch_id', $branchId);
            })
            ->select(
                'purchase_returns.*',
                'purchases.po_number',
                'purchases.invoice_number',
                'suppliers.name as supplier_name',
                'branches.name as branch_name',
                'users.name as admin_name',
                'accounts.name as account_name'
            )
            ->orderBy('purchase_returns.created_at', 'desc')
            ->get();

        if ($returns->isNotEmpty()) {
            $returnIds = $returns->pluck('id')->toArray();
            
            $items = DB::table('purchase_return_items')
                ->join('products', 'purchase_return_items.product_id', '=', 'products.id')
                ->whereIn('purchase_return_items.purchase_return_id', $returnIds)
                ->select(
                    'purchase_return_items.*',
                    'products.name as product_name',
                    'products.variant_name',
                    'products.sku as product_code'
                )
                ->get();

            foreach ($returns as $ret) {
                $ret->items = $items->where('purchase_return_id', $ret->id)->values()->toArray();
            }
        }

        return response()->json(['success' => true, 'data' => $returns]);
    }

    /**
     * 2. GET PO/FAKTUR YANG BISA DI-RETUR 
     */
    public function getEligiblePurchases(Request $request)
    {
        $user = $request->user();
        $branchId = ($user && $user->role !== 'owner') ? $user->branch_id : null;

        $purchases = DB::table('purchases')
            ->join('suppliers', 'purchases.supplier_id', '=', 'suppliers.id')
            ->whereIn('purchases.receipt_status', ['partial', 'completed']) 
            ->when($branchId, function ($query, $branchId) {
                return $query->where('purchases.branch_id', $branchId);
            })
            ->select(
                'purchases.id', 'purchases.po_number', 'purchases.invoice_number', 
                'purchases.status', 'purchases.payment_status', 'purchases.tax_type',
                'purchases.grand_total', 'purchases.paid_amount', 'purchases.dp_amount',
                'purchases.purchase_date', 
                'suppliers.id as supplier_id', 'suppliers.name as supplier_name'
            )
            ->orderBy('purchases.created_at', 'desc')
            ->get();

        if ($purchases->isNotEmpty()) {
            $purchaseIds = $purchases->pluck('id')->toArray();
            
            $items = DB::table('purchase_items')
                ->join('products', 'purchase_items.product_id', '=', 'products.id')
                ->whereIn('purchase_items.purchase_id', $purchaseIds)
                ->where('purchase_items.qty_received', '>', 0) 
                ->select(
                    'purchase_items.purchase_id',
                    'products.name as product_name',
                    'products.sku as product_code'
                )
                ->get();

            foreach ($purchases as $purchase) {
                $poItems = $items->where('purchase_id', $purchase->id);
                $purchase->product_names = $poItems->pluck('product_name')->implode(', ');
                $purchase->product_codes = $poItems->pluck('product_code')->implode(', ');
            }
        }

        return response()->json(['success' => true, 'data' => $purchases]);
    }

    /**
     * 3. GET ITEM DARI PO UNTUK DIRETUR 
     */
    public function getPurchaseItemsForReturn(Request $request, $purchaseId)
    {
        $user = $request->user();
        
        // PERBAIKAN ENTERPRISE: Validasi Otoritas Akses Dokumen
        $purchase = DB::table('purchases')->where('id', $purchaseId)->first();
        if (!$purchase || ($user && $user->role !== 'owner' && $purchase->branch_id !== $user->branch_id)) {
            return response()->json(['success' => false, 'message' => 'Dokumen tidak valid atau Anda tidak memiliki akses ke cabang ini.'], 403);
        }

        $items = DB::table('purchase_items')
            ->join('products', 'purchase_items.product_id', '=', 'products.id')
            ->where('purchase_items.purchase_id', $purchaseId)
            ->where('purchase_items.qty_received', '>', 0)
            ->select(
                'purchase_items.*', 
                'products.name as product_name', 
                'products.variant_name', 
                'products.sku as product_code'
            )
            ->get();

        $returnedItems = DB::table('purchase_return_items')
            ->join('purchase_returns', 'purchase_return_items.purchase_return_id', '=', 'purchase_returns.id')
            ->where('purchase_returns.purchase_id', $purchaseId)
            ->select('purchase_item_id', DB::raw('SUM(quantity) as total_returned'))
            ->groupBy('purchase_item_id')
            ->pluck('total_returned', 'purchase_item_id');

        $eligibleItems = [];

        foreach ($items as $item) {
            $alreadyReturned = $returnedItems[$item->id] ?? 0;
            $maxReturnable = $item->qty_received - $alreadyReturned;

            if ($maxReturnable > 0) {
                $item->max_returnable = $maxReturnable;
                $item->qty_to_return = 0; 
                $eligibleItems[] = $item;
            }
        }

        return response()->json(['success' => true, 'data' => $eligibleItems]);
    }

    /**
     * 4. PROSES SIMPAN RETUR PEMBELIAN 
     */
    public function store(Request $request)
    {
        $request->validate([
            'purchase_id' => 'required|integer',
            'return_date' => 'required|date',
            'return_type' => 'required|in:deduct_payable,cash_refund,replacement', 
            'items'       => 'required|array|min:1'
        ]);

        if ($request->return_type === 'cash_refund') {
            $request->validate(['refund_account_id' => 'required|integer']);
        }

        $user = $request->user();

        DB::beginTransaction();
        try {
            $purchase = DB::table('purchases')->where('id', $request->purchase_id)->first();
            if (!$purchase) throw new \Exception('Dokumen Pembelian tidak ditemukan.');

            // PERBAIKAN ENTERPRISE: Keamanan Eksekusi Retur Lintas Cabang
            if ($user && $user->role !== 'owner' && $purchase->branch_id !== $user->branch_id) {
                throw new \Exception('Akses ditolak: Dokumen ini bukan wewenang cabang Anda.');
            }

            // PERBAIKAN ENTERPRISE: Validasi Strict Account Mapping jika tipe Cash Refund
            if ($request->return_type === 'cash_refund') {
                $isMapped = DB::table('branch_accounts')
                    ->where('branch_id', $purchase->branch_id)
                    ->where('account_id', $request->refund_account_id)
                    ->where('is_active', 1)
                    ->exists();

                if (!$isMapped) {
                    throw new \Exception('Akses ditolak (Security Lock): Akun pencairan dana (Refund Account) yang dipilih tidak terdaftar/aktif untuk cabang ini.');
                }
            }

            $branchCode = DB::table('branches')->where('id', $purchase->branch_id)->value('code') ?? 'BR';
            $returnNumber = 'RB-' . $branchCode . '-' . date('YmdHis');

            $refundStatus = ($request->return_type === 'cash_refund') ? 'pending' : 'none';
            $replacementStatus = ($request->return_type === 'replacement') ? 'pending' : 'none'; 

            $returnId = DB::table('purchase_returns')->insertGetId([
                'branch_id'         => $purchase->branch_id,
                'supplier_id'       => $purchase->supplier_id,
                'purchase_id'       => $purchase->id,
                'user_id'           => $user->id,
                'return_number'     => $returnNumber,
                'return_date'       => $request->return_date,
                'return_type'       => $request->return_type,
                'refund_account_id' => $request->refund_account_id ?? null,
                'refund_status'     => $refundStatus, 
                'replacement_status'=> $replacementStatus,
                'notes'             => $request->notes,
                'total_amount'      => 0, 
                'created_at'        => Carbon::now(),
                'updated_at'        => Carbon::now()
            ]);

            $totalReturnItemValue = 0;

            foreach ($request->items as $reqItem) {
                $qtyToReturn = (float) $reqItem['qty_to_return'];
                if ($qtyToReturn <= 0) continue;

                $poItem = DB::table('purchase_items')->where('id', $reqItem['purchase_item_id'])->first();
                if (!$poItem) continue;

                $price = $poItem->is_bonus ? 0 : (float) $poItem->unit_price;
                $discountAmount = $this->calculateTieredDiscount($price, $poItem->discount_string);
                $netPrice = $price - $discountAmount;
                
                $rowTotalPrice = $netPrice * $qtyToReturn;
                $totalReturnItemValue += $rowTotalPrice;

                DB::table('purchase_return_items')->insert([
                    'purchase_return_id' => $returnId,
                    'purchase_item_id'   => $poItem->id,
                    'product_id'         => $poItem->product_id,
                    'quantity'           => $qtyToReturn,
                    'unit'               => $poItem->unit,
                    'conversion_value'   => $poItem->conversion_value,
                    'unit_price'         => $netPrice, 
                    'total_price'        => $rowTotalPrice,
                    'created_at'         => Carbon::now(),
                    'updated_at'         => Carbon::now()
                ]);

                // Kurangi Fisik Gudang
                $actualQtyToDeduct = $qtyToReturn * (float) $poItem->conversion_value;
                $stock = DB::table('product_stocks')
                    ->where('product_id', $poItem->product_id)
                    ->where('branch_id', $purchase->branch_id)
                    ->first();
                    
                if ($stock) {
                    DB::table('product_stocks')->where('id', $stock->id)->decrement('quantity', $actualQtyToDeduct);
                }

                $keteranganStok = 'Retur Pembelian: ' . $returnNumber;
                if ($request->return_type === 'replacement') {
                    $keteranganStok = 'Barang Keluar (Tukar Guling Supplier): ' . $returnNumber;
                }

                DB::table('stock_transactions')->insert([
                    'branch_id'       => $purchase->branch_id,
                    'product_id'      => $poItem->product_id,
                    'type'            => 'purchase_return',
                    'input_quantity'  => -$qtyToReturn,
                    'input_unit'      => $poItem->unit,
                    'actual_quantity' => -$actualQtyToDeduct,
                    'note'            => $keteranganStok,
                    'user_id'         => $user->id,
                    'created_at'      => Carbon::now(),
                    'updated_at'      => Carbon::now()
                ]);
            }

            $taxReturn = 0;
            $grandTotalReturn = 0;

            if ($purchase->tax_type === 'include') {
                $dpp = $totalReturnItemValue / 1.11;
                $taxReturn = $totalReturnItemValue - $dpp;
                $grandTotalReturn = $totalReturnItemValue;
            } elseif ($purchase->tax_type === 'exclude') {
                $taxReturn = $totalReturnItemValue * 0.11;
                $grandTotalReturn = $totalReturnItemValue + $taxReturn;
            } else {
                $grandTotalReturn = $totalReturnItemValue;
            }

            DB::table('purchase_returns')->where('id', $returnId)->update([
                'total_amount' => $grandTotalReturn
            ]);

            // ========================================================================
            // EKSEKUSI JURNAL VIA ACCOUNTING SERVICE (STORE RETURN) - STRICT GL
            // ========================================================================
            $inventoryAcc = AccountingService::getAccountId('persediaan_barang');
            if (!$inventoryAcc) throw new \Exception("Akun Persediaan Barang belum dikonfigurasi di Master Akun.");
            
            $journalItems = [];
            // (Kredit) Persediaan Keluar
            $journalItems[] = ['account_id' => $inventoryAcc, 'debit' => 0, 'credit' => $grandTotalReturn];

            if ($request->return_type === 'deduct_payable') {
                $payableAcc = AccountingService::getAccountId('hutang_usaha');
                if (!$payableAcc) throw new \Exception("Akun Hutang Usaha belum dikonfigurasi.");
                
                // (Debit) Hutang Berkurang
                $journalItems[] = ['account_id' => $payableAcc, 'debit' => $grandTotalReturn, 'credit' => 0];

                DB::table('debt_payments')->insert([
                    'purchase_id'    => $purchase->id,
                    'branch_id'      => $purchase->branch_id,
                    'user_id'        => $user->id,
                    'amount'         => $grandTotalReturn,
                    'account_id'     => $payableAcc, 
                    'payment_method' => 'return_deduction',
                    'payment_type'   => 'return_deduction',
                    'payment_date'   => $request->return_date,
                    'note'           => 'Potongan Retur No: ' . $returnNumber,
                    'created_at'     => Carbon::now(),
                    'updated_at'     => Carbon::now()
                ]);

                $actualPaid = max((float)$purchase->paid_amount, (float)$purchase->dp_amount);
                $newPaid = $actualPaid + $grandTotalReturn;
                $newStatus = ($newPaid >= $purchase->grand_total) ? 'paid' : 'partial';

                DB::table('purchases')->where('id', $purchase->id)->update([
                    'paid_amount'    => $newPaid,
                    'payment_status' => $newStatus,
                    'updated_at'     => Carbon::now()
                ]);

            } else {
                // UANG KEMBALI ATAU TUKAR GULING (Masuk ke Piutang Retur)
                $piutangReturId = AccountingService::getAccountId('piutang_retur_supplier');
                if (!$piutangReturId) {
                    $piutangReturAcc = DB::table('accounts')->where('name', 'Piutang Retur Supplier')->first();
                    if (!$piutangReturAcc) {
                        $piutangReturId = DB::table('accounts')->insertGetId([
                            'code' => '1105', 'name' => 'Piutang Retur Supplier', 'group' => 'asset',
                            'is_active' => 1, 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()
                        ]);
                    } else {
                        $piutangReturId = $piutangReturAcc->id;
                    }
                }

                // (Debit) Menambah Piutang Supplier / Klaim
                $journalItems[] = ['account_id' => $piutangReturId, 'debit' => $grandTotalReturn, 'credit' => 0];
            }

            AccountingService::log([
                'branch_id'   => $purchase->branch_id,
                'entry_date'  => $request->return_date,
                'description' => 'Retur Pembelian: ' . $returnNumber . ' (Ref PO: ' . $purchase->po_number . ')',
                'reference'   => $returnNumber,
                'source_type' => 'PURCHASE_RETURN',
                'user_id'     => $user->id,
                'items'       => $journalItems
            ]);
            // ========================================================================

            DB::commit();
            return response()->json([
                'success' => true, 
                'message' => 'Retur berhasil diproses. Stok dikurangi dan siap menunggu barang pengganti/uang.'
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false, 
                'message' => $e->getMessage()
            ]);
        }
    }

    /**
     * 5. TERIMA DANA REFUND (MENGGUNAKAN ACCOUNTING SERVICE)
     */
    public function receiveRefund(Request $request, $id)
    {
        $user = $request->user();

        DB::beginTransaction();
        try {
            $return = DB::table('purchase_returns')->where('id', $id)->first();
            if (!$return || $return->return_type !== 'cash_refund' || $return->refund_status !== 'pending') {
                throw new \Exception('Data Retur tidak valid atau dana sudah diterima.');
            }

            // PERBAIKAN ENTERPRISE: Keamanan Verifikasi Cabang
            if ($user && $user->role !== 'owner' && $return->branch_id !== $user->branch_id) {
                throw new \Exception('Akses ditolak: Anda tidak memiliki wewenang untuk menerima dana cabang lain.');
            }

            DB::table('purchase_returns')->where('id', $id)->update([
                'refund_status' => 'received',
                'updated_at'    => Carbon::now()
            ]);

            $piutangReturId = AccountingService::getAccountId('piutang_retur_supplier') ?? DB::table('accounts')->where('name', 'Piutang Retur Supplier')->value('id');

            // ========================================================================
            // EKSEKUSI JURNAL TERIMA DANA (ACCOUNTING SERVICE)
            // ========================================================================
            AccountingService::log([
                'branch_id'   => $return->branch_id,
                'entry_date'  => Carbon::now()->toDateString(),
                'description' => 'Terima Dana Retur Supplier: ' . $return->return_number,
                'reference'   => 'RCV-REFUND-' . $return->id,
                'source_type' => 'PURCHASE_REFUND_RCV',
                'user_id'     => $user->id,
                'items'       => [
                    ['account_id' => $return->refund_account_id, 'debit' => $return->total_amount, 'credit' => 0], // Kas/Bank Bertambah
                    ['account_id' => $piutangReturId, 'debit' => 0, 'credit' => $return->total_amount] // Piutang Retur Berkurang
                ]
            ]);
            // ========================================================================

            DB::commit();
            return response()->json(['success' => true, 'message' => 'Dana Retur berhasil dicatat masuk ke Kas/Bank.']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()]);
        }
    }

    /**
     * 6. TERIMA BARANG PENGGANTI (MENGGUNAKAN ACCOUNTING SERVICE)
     */
    public function receiveReplacement(Request $request, $id)
    {
        $user = $request->user();

        DB::beginTransaction();
        try {
            $return = DB::table('purchase_returns')->where('id', $id)->first();
            if (!$return || $return->return_type !== 'replacement' || $return->replacement_status !== 'pending') {
                throw new \Exception('Data Tukar Guling tidak valid atau barang sudah diterima.');
            }

            // PERBAIKAN ENTERPRISE: Keamanan Verifikasi Cabang
            if ($user && $user->role !== 'owner' && $return->branch_id !== $user->branch_id) {
                throw new \Exception('Akses ditolak: Anda tidak memiliki wewenang cabang ini.');
            }

            // Update status menjadi Diterima
            DB::table('purchase_returns')->where('id', $id)->update([
                'replacement_status' => 'received',
                'updated_at'         => Carbon::now()
            ]);

            // 1. Kembalikan Fisik Stok ke Gudang
            $returnItems = DB::table('purchase_return_items')->where('purchase_return_id', $id)->get();
            foreach ($returnItems as $item) {
                $actualQtyToRestore = $item->quantity * $item->conversion_value;
                
                $stock = DB::table('product_stocks')->where('product_id', $item->product_id)->where('branch_id', $return->branch_id)->first();
                if ($stock) {
                    DB::table('product_stocks')->where('id', $stock->id)->increment('quantity', $actualQtyToRestore);
                } else {
                    DB::table('product_stocks')->insert([
                        'product_id' => $item->product_id,
                        'branch_id'  => $return->branch_id,
                        'quantity'   => $actualQtyToRestore,
                        'created_at' => Carbon::now(),
                        'updated_at' => Carbon::now()
                    ]);
                }

                DB::table('stock_transactions')->insert([
                    'branch_id'       => $return->branch_id,
                    'product_id'      => $item->product_id,
                    'type'            => 'purchase_receipt',
                    'input_quantity'  => $item->quantity,
                    'input_unit'      => $item->unit,
                    'actual_quantity' => $actualQtyToRestore,
                    'note'            => 'Barang Masuk (Selesai Tukar Guling): ' . $return->return_number,
                    'user_id'         => $user->id,
                    'created_at'      => Carbon::now(),
                    'updated_at'      => Carbon::now()
                ]);
            }

            // ========================================================================
            // 2. JURNAL AKUNTANSI BARANG PENGGANTI (ACCOUNTING SERVICE)
            // ========================================================================
            $inventoryAcc = AccountingService::getAccountId('persediaan_barang');
            if (!$inventoryAcc) throw new \Exception("Akun Persediaan Barang belum dikonfigurasi.");
            
            $piutangReturId = AccountingService::getAccountId('piutang_retur_supplier') ?? DB::table('accounts')->where('name', 'Piutang Retur Supplier')->value('id');

            AccountingService::log([
                'branch_id'   => $return->branch_id,
                'entry_date'  => Carbon::now()->toDateString(),
                'description' => 'Terima Barang Pengganti (Tukar Guling): ' . $return->return_number,
                'reference'   => 'RCV-REPLACE-' . $return->id,
                'source_type' => 'REPLACEMENT_RCV',
                'user_id'     => $user->id,
                'items'       => [
                    ['account_id' => $inventoryAcc, 'debit' => $return->total_amount, 'credit' => 0], // Persediaan Bertambah
                    ['account_id' => $piutangReturId, 'debit' => 0, 'credit' => $return->total_amount] // Piutang Retur Berkurang
                ]
            ]);
            // ========================================================================

            DB::commit();
            return response()->json(['success' => true, 'message' => 'Barang pengganti berhasil diterima dan ditambahkan ke stok gudang.']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()]);
        }
    }

    /**
     * 7. VOID (BATALKAN) RETUR PEMBELIAN
     */
    public function destroy(Request $request, $id)
    {
        $user = $request->user();

        DB::beginTransaction();
        try {
            $return = DB::table('purchase_returns')->where('id', $id)->first();
            if (!$return) throw new \Exception('Data Retur tidak ditemukan.');

            // PERBAIKAN ENTERPRISE: Keamanan Eksekusi Silang Cabang
            if ($user && $user->role !== 'owner' && $return->branch_id !== $user->branch_id) {
                throw new \Exception('Akses ditolak: Anda tidak memiliki wewenang untuk membatalkan retur cabang ini.');
            }

            $purchase = DB::table('purchases')->where('id', $return->purchase_id)->first();

            // 1. Kembalikan Stok Gudang Fisik yang sempat ditarik
            $returnItems = DB::table('purchase_return_items')->where('purchase_return_id', $id)->get();
            foreach ($returnItems as $item) {
                $actualQtyToRollback = $item->quantity * $item->conversion_value;
                
                $stock = DB::table('product_stocks')->where('product_id', $item->product_id)->where('branch_id', $return->branch_id)->first();
                if ($stock) {
                    DB::table('product_stocks')->where('id', $stock->id)->increment('quantity', $actualQtyToRollback);
                }

                DB::table('stock_transactions')->insert([
                    'branch_id'       => $return->branch_id,
                    'product_id'      => $item->product_id,
                    'type'            => 'return_void',
                    'input_quantity'  => $item->quantity,
                    'input_unit'      => $item->unit,
                    'actual_quantity' => $actualQtyToRollback,
                    'note'            => 'BATAL Retur Pembelian: ' . $return->return_number,
                    'user_id'         => $user->id,
                    'created_at'      => Carbon::now(),
                    'updated_at'      => Carbon::now()
                ]);
            }

            // 2. Hapus Jurnal Akuntansi Retur Induk
            $journal = DB::table('journal_entries')->where('reference', $return->return_number)->where('source_type', 'PURCHASE_RETURN')->first();
            if ($journal) {
                DB::table('journal_items')->where('journal_entry_id', $journal->id)->delete();
                DB::table('journal_entries')->where('id', $journal->id)->delete();
            }

            if ($return->return_type === 'deduct_payable') {
                $virtualPayment = DB::table('debt_payments')
                    ->where('purchase_id', $purchase->id)
                    ->where('payment_method', 'return_deduction')
                    ->where('amount', $return->total_amount)
                    ->orderBy('id', 'desc')
                    ->first();

                if ($virtualPayment) {
                    DB::table('debt_payments')->where('id', $virtualPayment->id)->delete();

                    $newPaid = $purchase->paid_amount - $return->total_amount;
                    $newStatus = ($newPaid >= $purchase->grand_total) ? 'paid' : ($newPaid > (float)$purchase->dp_amount ? 'partial' : 'pending');

                    DB::table('purchases')->where('id', $purchase->id)->update([
                        'paid_amount'    => $newPaid,
                        'payment_status' => $newStatus,
                        'updated_at'     => Carbon::now()
                    ]);
                }
            } else {
                if ($return->refund_status === 'received') {
                    $journalRcv = DB::table('journal_entries')->where('reference', 'RCV-REFUND-' . $return->id)->first();
                    if ($journalRcv) {
                        DB::table('journal_items')->where('journal_entry_id', $journalRcv->id)->delete();
                        DB::table('journal_entries')->where('id', $journalRcv->id)->delete();
                    }
                }
                if ($return->replacement_status === 'received') {
                    $journalRep = DB::table('journal_entries')->where('reference', 'RCV-REPLACE-' . $return->id)->first();
                    if ($journalRep) {
                        DB::table('journal_items')->where('journal_entry_id', $journalRep->id)->delete();
                        DB::table('journal_entries')->where('id', $journalRep->id)->delete();
                    }
                    
                    // Tarik balik stok pengganti yang sudah sempat masuk
                    foreach ($returnItems as $item) {
                        $actualQtyToRollback = $item->quantity * $item->conversion_value;
                        $stock = DB::table('product_stocks')->where('product_id', $item->product_id)->where('branch_id', $return->branch_id)->first();
                        if ($stock) {
                            DB::table('product_stocks')->where('id', $stock->id)->decrement('quantity', $actualQtyToRollback);
                        }
                    }
                }
            }

            DB::table('purchase_return_items')->where('purchase_return_id', $id)->delete();
            DB::table('purchase_returns')->where('id', $id)->delete();

            DB::commit();
            return response()->json(['success' => true, 'message' => 'Retur dibatalkan. Stok dan Jurnal dikembalikan.']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()]);
        }
    }

    /**
     * HELPER DISKON 
     */
    private function calculateTieredDiscount($basePrice, $discountString)
    {
        if (empty($discountString)) return 0;
        $tiers = explode('+', strtolower(str_replace(' ', '', $discountString)));
        $currentPrice = $basePrice;
        
        foreach ($tiers as $tier) {
            if (str_contains($tier, '%')) {
                $percentage = (float) str_replace('%', '', $tier);
                if ($percentage > 0 && $percentage <= 100) $currentPrice -= ($currentPrice * ($percentage / 100));
            } else {
                $nominal = (float) str_replace(['rp', '.'], '', $tier);
                if ($nominal > 0) $currentPrice -= $nominal;
            }
        }
        return $basePrice - ($currentPrice < 0 ? 0 : $currentPrice);
    }
}