<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\RawMaterialTransfer;
use App\Models\RawMaterialTransferItem;
use App\Models\Warehouse;
use App\Models\Product;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class RawMaterialTransferController extends Controller
{
    public function index()
    {
        $transfers = RawMaterialTransfer::with(['fromWarehouse', 'toWarehouse'])
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        return view('transfer.raw-material.index', compact('transfers'));
    }

    public function create()
    {
        $warehouses = Warehouse::where('status', 1)->get();

        $products = Product::query()
            ->when(Schema::hasColumn('products', 'status'), fn ($q) => $q->where('status', 1))
            ->when(Schema::hasColumn('products', 'type'), fn ($q) => $q->where('type', 'raw_material'))
            ->get();

        return view('transfer.raw-material.create', compact('warehouses', 'products'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'from_warehouse' => 'required|exists:warehouses,id',
            'to_warehouse'   => 'required|exists:warehouses,id|different:from_warehouse',
            'date'           => 'required|date',
            'transfer_cost'  => 'nullable|numeric|min:0',
            'items'                 => 'required|array|min:1',
            'items.*.product_id'    => 'required|exists:products,id',
            'items.*.kg'            => 'nullable|numeric|min:0',
            'items.*.bag'           => 'nullable|numeric|min:0',
            'items.*.total_kg'      => 'nullable|numeric|min:0',
            'items.*.mon'           => 'nullable|numeric|min:0',
        ]);

        DB::beginTransaction();
        try {
            $transfer = RawMaterialTransfer::create([
                'from_warehouse_id' => $request->from_warehouse,
                'to_warehouse_id'   => $request->to_warehouse,
                'date'              => $request->date,
                'transfer_cost'     => $request->transfer_cost ?? 0,
                'total_kg'          => 0,
                'total_bag'         => 0,
                'grand_total_kg'    => 0,
                'status'            => 'pending',
            ]);

            $totalKg = 0; $totalBag = 0; $grandTotalKg = 0;

            foreach ($request->items as $item) {
                if (!empty($item['product_id'])) {
                    $kg = $item['kg'] ?? 0;
                    $bag = $item['bag'] ?? 0;
                    $total_kg = $item['total_kg'] ?? 0;
                    $mon = $item['mon'] ?? 0;

                    RawMaterialTransferItem::create([
                        'raw_material_transfer_id' => $transfer->id,
                        'product_id'               => $item['product_id'],
                        'kg'                       => $kg,
                        'bag'                      => $bag,
                        'total_kg'                 => $total_kg,
                        'mon'                      => $mon,
                    ]);

                    $totalKg += $kg;
                    $totalBag += $bag;
                    $grandTotalKg += $total_kg;
                }
            }

            $transfer->update([
                'total_kg'       => $totalKg,
                'total_bag'      => $totalBag,
                'grand_total_kg' => $grandTotalKg,
            ]);

            DB::commit();

            return redirect()->route('transfer.raw-material.index')
                ->with('success', 'Raw Material Transfer created successfully!');
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->back()
                ->with('error', 'Error creating transfer: ' . $e->getMessage())
                ->withInput();
        }
    }

    public function edit($id)
    {
        $transfer   = RawMaterialTransfer::with('items.product')->findOrFail($id);
        $warehouses = Warehouse::where('status', 1)->get();

        $products = Product::query()
            ->when(Schema::hasColumn('products', 'status'), fn ($q) => $q->where('status', 1))
            ->when(Schema::hasColumn('products', 'type'), fn ($q) => $q->where('type', 'raw_material'))
            ->get();

        return view('transfer.raw-material.edit', compact('transfer', 'warehouses', 'products'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'from_warehouse' => 'required|exists:warehouses,id',
            'to_warehouse'   => 'required|exists:warehouses,id|different:from_warehouse',
            'date'           => 'required|date',
            'transfer_cost'  => 'nullable|numeric|min:0',
            'items'                 => 'required|array|min:1',
            'items.*.product_id'    => 'required|exists:products,id',
            'items.*.kg'            => 'nullable|numeric|min:0',
            'items.*.bag'           => 'nullable|numeric|min:0',
            'items.*.total_kg'      => 'nullable|numeric|min:0',
            'items.*.mon'           => 'nullable|numeric|min:0',
        ]);

        DB::beginTransaction();
        try {
            $transfer = RawMaterialTransfer::findOrFail($id);

            $transfer->update([
                'from_warehouse_id' => $request->from_warehouse,
                'to_warehouse_id'   => $request->to_warehouse,
                'date'              => $request->date,
                'transfer_cost'     => $request->transfer_cost ?? 0,
            ]);

            $transfer->items()->delete();

            $totalKg = 0; $totalBag = 0; $grandTotalKg = 0;

            foreach ($request->items as $item) {
                if (!empty($item['product_id'])) {
                    $kg = $item['kg'] ?? 0;
                    $bag = $item['bag'] ?? 0;
                    $total_kg = $item['total_kg'] ?? 0;
                    $mon = $item['mon'] ?? 0;

                    RawMaterialTransferItem::create([
                        'raw_material_transfer_id' => $transfer->id,
                        'product_id'               => $item['product_id'],
                        'kg'                       => $kg,
                        'bag'                      => $bag,
                        'total_kg'                 => $total_kg,
                        'mon'                      => $mon,
                    ]);

                    $totalKg += $kg;
                    $totalBag += $bag;
                    $grandTotalKg += $total_kg;
                }
            }

            $transfer->update([
                'total_kg'       => $totalKg,
                'total_bag'      => $totalBag,
                'grand_total_kg' => $grandTotalKg,
            ]);

            DB::commit();

            return redirect()->route('transfer.raw-material.index')
                ->with('success', 'Raw Material Transfer updated successfully!');
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->back()
                ->with('error', 'Error updating transfer: ' . $e->getMessage())
                ->withInput();
        }
    }

    public function destroy($id)
    {
        DB::beginTransaction();
        try {
            $transfer = RawMaterialTransfer::findOrFail($id);
            $transfer->items()->delete();
            $transfer->delete();

            DB::commit();

            return redirect()->route('transfer.raw-material.index')
                ->with('success', 'Raw Material Transfer deleted successfully!');
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->back()
                ->with('error', 'Error deleting transfer: ' . $e->getMessage());
        }
    }
}
