<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\ProductPrice;
use App\Models\Branch;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\QueryException; 

class AdminProductController extends Controller
{
    // 1. Tampilkan Data Produk (HANYA INDUK)
    public function index(Request $request) {
        $user = $request->user();
        
        // Load relasi prices
        $query = Product::with(['category', 'branches', 'prices'])
            ->where(function($q) {
                // Mencegah anak varian bocor ke tabel utama
                $q->whereNull('variant_group_id')->orWhere('variant_group_id', '');
            })
            ->orderBy('created_at', 'desc');
        
        if ($user->role !== 'owner') {
            $query->whereHas('branches', function ($q) use ($user) {
                $q->where('branches.id', $user->branch_id);
            });
        }
        
        $products = $query->get()->map(function($product) {
            
            // --- 1. SUSUN HARGA PRODUK INDUK (Jika Tidak Ada Varian) ---
            $priceMatrix = [];
            if ($product->prices && $product->prices->isNotEmpty()) {
                $grouped = $product->prices->groupBy('level');
                foreach ($grouped as $level => $items) {
                    $row = ['level_id' => $level, 'id' => count($priceMatrix) + 1, 'min_online_qty' => '', 'price_l1' => '', 'price_l2' => '', 'price_l3' => '', 'price_l4' => ''];
                    foreach ($items as $item) {
                        if (!empty($item->min_online_qty)) $row['min_online_qty'] = $item->min_online_qty;
                        if ($item->unit_level == 1) $row['price_l1'] = $item->amount;
                        if ($item->unit_level == 2) $row['price_l2'] = $item->amount;
                        if ($item->unit_level == 3) $row['price_l3'] = $item->amount;
                        if ($item->unit_level == 4) $row['price_l4'] = $item->amount;
                    }
                    $priceMatrix[] = $row;
                }
            }
            $product->price_matrix = empty($priceMatrix) ? null : $priceMatrix;

            // --- 2. CARI DATA VARIAN ANAK DI DATABASE ---
            $groupId = 'VAR-' . $product->id;
            $children = \App\Models\Product::with('prices')->where('variant_group_id', $groupId)->get();

            if ($children->count() > 0) {
                $product->has_variants = true;
                $variantsList = [];
                
                foreach ($children as $child) {
                    $childMatrix = [];
                    // Susun harga milik si Anak
                    if ($child->prices && $child->prices->isNotEmpty()) {
                        $groupedChild = $child->prices->groupBy('level');
                        foreach ($groupedChild as $level => $items) {
                            $row = ['level_id' => $level, 'id' => count($childMatrix) + 1, 'min_online_qty' => '', 'price_l1' => '', 'price_l2' => '', 'price_l3' => '', 'price_l4' => ''];
                            foreach ($items as $item) {
                                if (!empty($item->min_online_qty)) $row['min_online_qty'] = $item->min_online_qty;
                                if ($item->unit_level == 1) $row['price_l1'] = $item->amount;
                                if ($item->unit_level == 2) $row['price_l2'] = $item->amount;
                                if ($item->unit_level == 3) $row['price_l3'] = $item->amount;
                                if ($item->unit_level == 4) $row['price_l4'] = $item->amount;
                            }
                            $childMatrix[] = $row;
                        }
                    }

                    $variantsList[] = [
                        'id' => $child->id,
                        'variant_name' => $child->variant_name,
                        'sku' => $child->sku,
                        'product_type' => $child->product_type ?? 'trading', 
                        'buy_price' => $child->buy_price,
                        'unit' => $child->unit,
                        'buy_unit' => $child->buy_unit,
                        'conversion_factor' => $child->conversion_factor,
                        'unit_3_name' => $child->unit_3_name,
                        'conversion_3_qty' => $child->conversion_3_qty,
                        'unit_4_name' => $child->unit_4_name,
                        'conversion_4_qty' => $child->conversion_4_qty,
                        'price_reference_level' => $child->price_reference_level,
                        'price_matrix' => empty($childMatrix) ? null : $childMatrix, 
                    ];
                }
                $product->variants_list = $variantsList;
            } else {
                $product->has_variants = false;
                $product->variants_list = [];
            }

            $product->unsetRelation('prices'); 
            
            // --- 3. FORMAT RETURN INDUK ---
            return [
                'id' => $product->id,
                'sku' => $product->sku,
                'name' => $product->name,
                'product_type' => $product->product_type ?? 'trading', 
                'category' => $product->category ? $product->category->name : '-',
                'category_id' => $product->category_id,
                'unit' => $product->unit,
                'buy_price' => $product->buy_price,
                'buy_unit' => $product->buy_unit,
                'conversion_factor' => $product->conversion_factor,
                'unit_3_name' => $product->unit_3_name,
                'conversion_3_qty' => $product->conversion_3_qty,
                'unit_4_name' => $product->unit_4_name,
                'conversion_4_qty' => $product->conversion_4_qty,
                'is_active' => $product->is_active,
                'is_available_online' => $product->is_available_online,
                'image_url' => $product->image_path ? asset('storage/' . $product->image_path) : null,
                'image_path' => $product->image_path, // Tambahan untuk merender gambar di PWA/Frontend
                'branches' => $product->branches->pluck('id'),
                'price_reference_level' => $product->price_reference_level,
                'has_variants' => $product->has_variants,
                'variants_list' => $product->variants_list,
                'price_matrix' => $product->price_matrix,
            ];
        });

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

    public function getBranches(Request $request) {
        $user = $request->user();
        
        // Isolasi Dropdown Cabang
        if ($user && $user->role !== 'owner') {
            $branches = Branch::where('id', $user->branch_id)->get();
        } else {
            $branches = Branch::orderBy('name', 'asc')->get();
        }
        
        return response()->json(['success' => true, 'data' => $branches]);
    }

    public function store(Request $request) { 
        return $this->saveProduct($request, new Product()); 
    }
    
    public function update(Request $request, $id) { 
        $user = $request->user();
        $product = Product::findOrFail($id);

        if ($user && $user->role !== 'owner') {
            $isMyBranch = $product->branches()->where('branches.id', $user->branch_id)->exists();
            if (!$isMyBranch) {
                return response()->json([
                    'success' => false, 
                    'message' => 'Akses ditolak: Anda tidak memiliki hak akses mengubah produk milik cabang lain.'
                ], 403);
            }
        }

        return $this->saveProduct($request, $product); 
    }

    private function saveProduct(Request $request, Product $product) {
        $request->validate([
            'name' => 'required|string|max:255',
            'product_type' => 'nullable|in:trading,raw_material,consumable,finished_good',
            'category_id' => 'required|integer',
            'buy_price' => 'nullable|numeric|min:0',
            'unit' => 'required|string|max:50',
            'branches' => 'nullable|json',
            'variants_list' => 'nullable|json',
            'price_matrix' => 'nullable|json',
            'image' => 'nullable|image|mimes:jpeg,png,jpg|max:2048'
        ]);

        try {
            DB::beginTransaction();

            $isNewRecord = !$product->exists;

            $product->name = $request->name;
            $product->product_type = $request->product_type ?? ($product->product_type ?? 'trading'); 
            $product->category_id = $request->category_id;
            $product->is_active = $request->boolean('is_active');
            $product->is_available_online = $request->boolean('is_available_online');
            if ($request->filled('sku')) $product->sku = $request->sku;
            
            $product->buy_price = $request->buy_price ?: 0;
            
            // PERBAIKAN 1: Set Average Cost awal untuk produk baru agar jurnal akuntansi valid
            if ($isNewRecord) {
                $product->average_cost = $request->buy_price ?: 0;
            }

            $product->unit = $request->unit;
            $product->buy_unit = $request->buy_unit;
            $product->conversion_factor = $request->conversion_factor ?: null;
            $product->unit_3_name = $request->unit_3_name;
            $product->conversion_3_qty = $request->conversion_3_qty ?: null;
            $product->unit_4_name = $request->unit_4_name;
            $product->conversion_4_qty = $request->conversion_4_qty ?: null;
            $product->price_reference_level = $request->price_reference_level ?: 1;

            if ($request->hasFile('image')) {
                if ($product->image_path) Storage::disk('public')->delete($product->image_path);
                $product->image_path = $request->file('image')->store('products', 'public');
            }

            $product->save(); 

            $hasVariants = $request->boolean('has_variants');

            // === A. PROSES JIKA ADA VARIAN ===
            if ($hasVariants) {
                $variantsList = json_decode($request->variants_list, true) ?: [];
                $groupId = 'VAR-' . $product->id;
                $keptIds = [];

                foreach ($variantsList as $varData) {
                    $sku = !empty($varData['sku']) ? $varData['sku'] : 'VAR' . date('ymd') . mt_rand(1000, 9999);
                    
                    $childId = $varData['id'] ?? null;
                    if ($childId) {
                        $child = Product::find($childId);
                        if (!$child) $child = new Product();
                    } else {
                        $child = Product::firstOrNew(['variant_group_id' => $groupId, 'sku' => $sku]);
                    }
                    
                    $isNewChild = !$child->exists;

                    $child->variant_group_id = $groupId;
                    $child->sku = $sku;
                    $child->name = $product->name;
                    $child->product_type = $product->product_type; 
                    $child->variant_name = $varData['variant_name'];
                    $child->category_id = $product->category_id;
                    $child->is_active = $product->is_active;
                    $child->is_available_online = $product->is_available_online;
                    $child->image_path = $product->image_path;
                    
                    $child->buy_price = !empty($varData['buy_price']) ? $varData['buy_price'] : $product->buy_price;
                    
                    if ($isNewChild) {
                        $child->average_cost = $child->buy_price;
                    }

                    $child->unit = $varData['unit'] ?? 'PCS'; 
                    $child->buy_unit = $varData['buy_unit'] ?? null; 
                    $child->conversion_factor = $varData['conversion_factor'] ?: null;
                    $child->unit_3_name = $varData['unit_3_name'] ?? null; 
                    $child->conversion_3_qty = $varData['conversion_3_qty'] ?: null;
                    $child->unit_4_name = $varData['unit_4_name'] ?? null; 
                    $child->conversion_4_qty = $varData['conversion_4_qty'] ?: null;
                    $child->price_reference_level = $varData['price_reference_level'] ?? 1;
                    
                    $child->save();

                    // Mencegah array branch kosong/null tersimpan di database pivot
                    $user = auth()->user();
                    if ($request->filled('branches')) {
                        $branchIds = $user->role === 'owner' ? json_decode($request->branches, true) : [$user->branch_id];
                        $validBranchIds = array_filter((array)$branchIds, function($val) { return !is_null($val) && $val !== ''; });
                        $child->branches()->sync($validBranchIds);
                    } else {
                        if ($user && !empty($user->branch_id)) $child->branches()->sync([$user->branch_id]);
                    }
                    
                    // PERBAIKAN 2: Blokir harga jual untuk varian jika tipenya Bahan Baku/Penolong
                    if (in_array($child->product_type, ['raw_material', 'consumable'])) {
                        $childMatrix = []; 
                    } else {
                        $childMatrix = $varData['price_matrix'] ?? [];
                    }
                    
                    $this->syncProductPrices($child->id, $childMatrix);
                    $keptIds[] = $child->id;
                }
                
                Product::where('variant_group_id', $groupId)->whereNotIn('id', $keptIds)->delete();
                
            } 
            // === B. PROSES JIKA TIDAK ADA VARIAN ===
            else {
                Product::where('variant_group_id', 'VAR-' . $product->id)->delete(); 
                
                // PERBAIKAN 2: Blokir harga jual untuk produk induk jika tipenya Bahan Baku/Penolong
                if (in_array($product->product_type, ['raw_material', 'consumable'])) {
                    $matrix = [];
                } else {
                    $matrix = json_decode($request->price_matrix, true);
                }

                $this->syncProductPrices($product->id, $matrix);
            }

            // Mencegah array branch kosong/null tersimpan di database pivot
            $user = auth()->user();
            if ($request->filled('branches')) {
                $branchIds = $user->role === 'owner' ? json_decode($request->branches, true) : [$user->branch_id];
                $validBranchIds = array_filter((array)$branchIds, function($val) { return !is_null($val) && $val !== ''; });
                $product->branches()->sync($validBranchIds);
            } else {
                if ($user && !empty($user->branch_id)) $product->branches()->sync([$user->branch_id]);
            }

            DB::commit();
            return response()->json(['success' => true, 'message' => 'Data Produk berhasil disinkronisasi.']);
            
        } catch (QueryException $e) {
            DB::rollBack();
            if ($e->getCode() == "23000") {
                return response()->json([
                    'success' => false, 
                    'message' => 'Gagal menyimpan: Anda mencoba menghapus atau mengganti varian produk yang sudah memiliki riwayat transaksi/stok di database. Silakan kembalikan varian tersebut dan cukup nonaktifkan status aktifnya.'
                ], 400);
            }
            return response()->json(['success' => false, 'message' => 'Database Error: ' . $e->getMessage()], 500);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    private function syncProductPrices($productId, $priceMatrix) {
        ProductPrice::where('product_id', $productId)->delete(); 
        
        if (empty($priceMatrix)) return;

        foreach ($priceMatrix as $row) {
            $level = $row['level_id'] ?? $row['level'] ?? null;
            if (!$level) continue;

            $minOnlineQty = $row['min_online_qty'] ?? null;
            $valL1 = $row['price_l1'] ?? $row['amount'] ?? null;

            $baseData = ['product_id' => $productId, 'level' => $level, 'min_online_qty' => $minOnlineQty];
            
            if (isset($valL1) && $valL1 !== '') ProductPrice::create(array_merge($baseData, ['unit_level' => 1, 'amount' => (float)$valL1]));
            if (isset($row['price_l2']) && $row['price_l2'] !== '') ProductPrice::create(array_merge($baseData, ['unit_level' => 2, 'amount' => (float)$row['price_l2']]));
            if (isset($row['price_l3']) && $row['price_l3'] !== '') ProductPrice::create(array_merge($baseData, ['unit_level' => 3, 'amount' => (float)$row['price_l3']]));
            if (isset($row['price_l4']) && $row['price_l4'] !== '') ProductPrice::create(array_merge($baseData, ['unit_level' => 4, 'amount' => (float)$row['price_l4']]));
        }
    }
    
    public function destroy($id) {
        DB::beginTransaction();
        try {
            $user = auth()->user();
            $product = Product::findOrFail($id);

            if ($user->role !== 'owner') {
                 $isMyBranch = $product->branches()->where('branches.id', $user->branch_id)->exists();
                 if (!$isMyBranch) {
                      return response()->json(['success' => false, 'message' => 'Akses ditolak: Anda tidak memiliki hak akses menghapus produk cabang lain.'], 403);
                 }
            }

            if ($product->image_path) Storage::disk('public')->delete($product->image_path);
            
            Product::where('variant_group_id', 'VAR-' . $product->id)->delete(); 
            $product->branches()->detach();
            $product->delete();
            
            DB::commit();
            return response()->json(['success' => true, 'message' => 'Produk dihapus secara permanen.']);
            
        } catch (QueryException $e) {
            DB::rollBack();
            if ($e->getCode() == "23000") {
                return response()->json([
                    'success' => false, 
                    'message' => 'Gagal menghapus: Produk ini sudah memiliki riwayat transaksi (Penjualan/Pembelian/Mutasi Stok) di sistem. Silakan nonaktifkan status produk ini alih-alih menghapusnya.'
                ], 400);
            }
            return response()->json(['success' => false, 'message' => 'Database Error: ' . $e->getMessage()], 500);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}