<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Models\StockHistory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class StockHistoryController extends Controller
{
    // ── INDEX (semua produk) ──────────────────────────────────────────────────

    public function index(Request $request)
    {
        $query = StockHistory::with(['product.category', 'user'])->latest();

        if ($request->filled('search')) {
            $query->whereHas('product', fn($q) =>
                $q->where('product_name', 'like', '%' . $request->search . '%')
            );
        }

        if ($request->filled('type')) {
            $query->where('type', $request->type);
        }

        if ($request->filled('source')) {
            $query->where('source', $request->source);
        }

        $histories     = $query->paginate(20);
        $products      = Product::orderBy('product_name')->get();
        $totalIn       = StockHistory::where('type', 'in')->sum('quantity');
        $totalOut      = StockHistory::where('type', 'out')->sum('quantity');
        $totalProducts = Product::count();

        return view('product.admin.stock-history', compact(
            'histories', 'products', 'totalIn', 'totalOut', 'totalProducts'
        ));
    }

    // ── HISTORY PER PRODUK ────────────────────────────────────────────────────

    public function history($product_id)
    {
        $product   = Product::findOrFail($product_id);
        $histories = StockHistory::where('product_id', $product_id)
                                 ->with('user')
                                 ->latest()
                                 ->paginate(15);

        $products      = Product::orderBy('product_name')->get();
        $totalIn       = StockHistory::where('product_id', $product_id)->where('type', 'in')->sum('quantity');
        $totalOut      = StockHistory::where('product_id', $product_id)->where('type', 'out')->sum('quantity');
        $totalProducts = Product::count();

        return view('product.admin.stock-history', compact(
            'product', 'histories', 'products', 'totalIn', 'totalOut', 'totalProducts'
        ));
    }

    // ── ✅ UNIFIED STOCK ACTION (restock + adjustment dalam satu endpoint) ────

    public function stockAction(Request $request)
    {
        $request->validate([
            'action_type' => 'required|in:restock,adjustment',
            'product_id'  => 'required|exists:tbl_product,product_id',
            'quantity'    => 'required|integer|min:1',
            'adj_type'    => 'required_if:action_type,adjustment|in:in,out',
            'note'        => 'required_if:action_type,adjustment|nullable|string|max:500',
        ], [
            'adj_type.required_if' => 'Pilih tipe (Tambah/Kurang) untuk penyesuaian.',
            'note.required_if'     => 'Alasan wajib diisi untuk penyesuaian stok.',
        ]);

        DB::transaction(function () use ($request) {
            $product     = Product::lockForUpdate()->findOrFail($request->product_id);
            $isRestock   = $request->action_type === 'restock';
            $type        = $isRestock ? 'in' : $request->adj_type;
            $stockBefore = $product->stock;

            if ($type === 'out' && $stockBefore < $request->quantity) {
                abort(422, 'Stok tidak mencukupi untuk dikurangi.');
            }

            $stockAfter = $type === 'in'
                ? $stockBefore + $request->quantity
                : $stockBefore - $request->quantity;

            $product->update(['stock' => $stockAfter]);

            StockHistory::create([
                'product_id'   => $product->product_id,
                'user_id'      => Auth::id(),
                'type'         => $type,
                'source'       => $isRestock ? 'manual' : 'adjustment',
                'quantity'     => $request->quantity,
                'stock_before' => $stockBefore,
                'stock_after'  => $stockAfter,
                'note'         => $request->filled('note')
                                    ? $request->note
                                    : ($isRestock ? 'Restock stok produk' : null),
            ]);
        });

        return back()->with('success',
            $request->action_type === 'restock'
                ? 'Stok berhasil ditambahkan.'
                : 'Stok berhasil disesuaikan.'
        );
    }

    // ── Legacy routes (tetap ada agar tidak break route lama) ────────────────

    public function restock(Request $request, $product_id = null)
    {
        if (is_null($product_id)) {
            $request->merge(['action_type' => 'restock']);
        } else {
            $request->merge(['action_type' => 'restock', 'product_id' => $product_id]);
        }
        return $this->stockAction($request);
    }

    public function adjustment(Request $request, $product_id = null)
    {
        if (!is_null($product_id)) {
            $request->merge(['product_id' => $product_id]);
        }
        $request->merge(['action_type' => 'adjustment']);
        return $this->stockAction($request);
    }
}