<?php

namespace App\Http\Controllers\Api;

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

class StockMutationController extends Controller
{
    /**
     * Memindahkan stok bagus (quantity) ke stok rusak (bs_quantity)
     */
    public function quarantine(Request $request)
    {
        $request->validate([
            'branch_id' => 'required',
            'mutation_date' => 'required|date',
            'notes' => 'nullable|string',
            'items' => 'required|array|min:1',
            'items.*.product_id' => 'required',
            'items.*.qty' => 'required|numeric|min:1',
        ]);

        try {
            return DB::transaction(function () use ($request) {
                $user = auth()->user();
                
                // PERBAIKAN ENTERPRISE: Proteksi Manipulasi Lintas Cabang (IDOR Protection)
                $branchId = ($user && $user->role !== 'owner') ? $user->branch_id : $request->branch_id;

                $totalValue = 0;
                $productDetails = [];
                
                $dateCode = Carbon::parse($request->mutation_date)->format('Y/m');
                $docNumber = "QRN/{$dateCode}/" . rand(1000, 9999); 

                foreach ($request->items as $item) {
                    $product = DB::table('products')->where('id', $item['product_id'])->first();
                    
                    // 1. Buat nama lengkap (Nama + Varian) untuk Jurnal
                    $fullName = $product ? (strtoupper($product->name) . ($product->variant_name ? " - " . strtoupper($product->variant_name) : "")) : "ID " . $item['product_id'];
                    $productDetails[] = $fullName; 

                    // 2. Buat nama produk untuk Error Message (tetap sesuai kode asli Anda)
                    $productName = $product ? strtoupper($product->name) : "ID " . $item['product_id'];

                    // === KALKULASI KONVERSI SATUAN STRICT FLOAT ===
                    $multiplier = 1.00;
                    $selectedUnit = strtoupper($item['unit'] ?? 'PCS');
                    
                    if ($selectedUnit === strtoupper($product->buy_unit ?? '')) {
                        $multiplier = (float)($product->conversion_factor ?? 1);
                    } elseif ($selectedUnit === strtoupper($product->unit_3_name ?? '')) {
                        $multiplier = (float)($product->conversion_3_qty ?? 1);
                    } elseif ($selectedUnit === strtoupper($product->unit_4_name ?? '')) {
                        $multiplier = (float)($product->conversion_4_qty ?? 1);
                    }

                    $baseQty = (float)$item['qty'] * $multiplier;

                    // === KUNCI DATABASE & CEK STOK ===
                    $stock = DB::table('product_stocks')
                        ->where('product_id', $item['product_id'])
                        ->where('branch_id', $branchId)
                        ->lockForUpdate()
                        ->first();

                    $currentQty = $stock ? (float)$stock->quantity : 0.00;
                    $baseUnit = strtoupper($product->unit ?? 'PCS'); // Ambil satuan dasar / terkecil dari master produk

                    if (!$stock || $currentQty < $baseQty) {
                        // Logika Pesan Error Dinamis Standar Enterprise
                        if ($selectedUnit !== $baseUnit) {
                            // Jika satuan yang dipilih admin berbeda dengan satuan dasar (contoh: minta DUS, stok dalam PCS)
                            throw new \Exception("Stok {$productName} tidak cukup! (Diminta: {$item['qty']} {$selectedUnit} / setara {$baseQty} {$baseUnit}, Tersedia: {$currentQty} {$baseUnit})");
                        } else {
                            // Jika satuan yang dipilih sudah sama dengan satuan dasar
                            throw new \Exception("Stok {$productName} tidak cukup! (Diminta: {$baseQty} {$baseUnit}, Tersedia: {$currentQty} {$baseUnit})");
                        }
                    }

                    // === EKSEKUSI PEMOTONGAN AMAN ===
                    DB::table('product_stocks')->where('id', $stock->id)->update([
                        'quantity' => $currentQty - $baseQty,
                        'bs_quantity' => (float)$stock->bs_quantity + $baseQty,
                        'updated_at' => now()
                    ]);

                    // === AUDIT TRAIL ===
                    DB::table('stock_transactions')->insert([
                        'branch_id' => $branchId,
                        'product_id' => $item['product_id'],
                        'type' => 'quarantine_bs',
                        'input_quantity' => (float)$item['qty'],
                        'input_unit' => $selectedUnit,
                        'actual_quantity' => -$baseQty, 
                        'note' => "Karantina BS: " . ($item['notes'] ?? $request->notes),
                        'user_id' => $user->id ?? 1,
                        'created_at' => now()
                    ]);

                    // PERBAIKAN: Gunakan Moving Average Cost (HPP Rata-Rata) untuk valuasi perpindahan aset
                    $hppItem = (isset($product->average_cost) && $product->average_cost > 0) ? (float) $product->average_cost : (float) ($product->buy_price ?? 0);
                    $totalValue += ($hppItem * $baseQty);
                }

                // =========================================================================
                // JURNAL AKUNTANSI REKLASIFIKASI PERSEDIAAN (STRICT GL)
                // =========================================================================
                if ($totalValue > 0) {
                    $akunPersediaanBagus = AccountingService::getAccountId('inventory_account');  
                    $akunPersediaanBS = AccountingService::getAccountId('bs_inventory_account');    

                    if (!$akunPersediaanBagus || !$akunPersediaanBS) {
                        throw new \Exception("Sistem Gagal: Master Akun Persediaan Bagus / Persediaan BS belum dikonfigurasi.");
                    }

                    AccountingService::log([
                        'branch_id'   => $branchId,
                        'entry_date'  => $request->mutation_date,
                        'description' => "Karantina BS: " . implode(", ", array_unique($productDetails)) . " | " . $request->notes,
                        'reference'   => $docNumber,
                        'source_type' => 'BS_QUARANTINE',
                        'user_id'     => $user->id ?? 1,
                        'items'       => [
                            ['account_id' => $akunPersediaanBS, 'debit' => $totalValue, 'credit' => 0],
                            ['account_id' => $akunPersediaanBagus, 'debit' => 0, 'credit' => $totalValue]
                        ]
                    ]);
                }
                // =========================================================================

                return response()->json([
                    'success' => true, 
                    'message' => 'Barang berhasil dipindahkan ke area karantina dan dijurnal.',
                    'doc_number' => $docNumber
                ]);
            });
        } catch (\Exception $e) {
            Log::error("Quarantine BS Error: " . $e->getMessage());
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * MENDAPATKAN DAFTAR STOK KARANTINA YANG BELUM DIMUSNAHKAN
     */
    public function getQuarantinedStocks(Request $request)
    {
        try {
            $user = auth()->user();
            $query = DB::table('product_stocks as ps')
                ->join('products as p', 'ps.product_id', '=', 'p.id')
                ->join('branches as b', 'ps.branch_id', '=', 'b.id')
                ->select(
                    'ps.*', 
                    'p.sku', 
                    'p.name as product_name', 
                    'p.variant_name', 
                    'p.unit as satuan_dasar',  // <--- KITA KUNCI NAMANYA JADI 'satuan_dasar'
                    'b.name as branch_name'
                )
                ->where('ps.bs_quantity', '>', 0)
                ->orderBy('b.name')
                ->orderBy('p.name');

            // PERBAIKAN ENTERPRISE: Isolasi Tabel Karantina
            if ($user && $user->role !== 'owner') {
                $query->where('ps.branch_id', $user->branch_id);
            }

            return response()->json([
                'success' => true,
                'data' => $query->get()
            ]);
        } catch (\Exception $e) {
            Log::error("Get Quarantined Stocks Error: " . $e->getMessage());
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}