<?php

namespace App\Http\Controllers;

use App\Models\Branch;
use App\Models\Product;
use App\Models\ProductStock;
use App\Models\StockMutation;
use App\Models\Supplier;
use App\Services\InventoryService;
use Illuminate\Http\Request;

class InventoryController extends Controller
{
    public function index(Request $request)
    {
        $branchId = $request->user()->isOwner() ? $request->integer('branch_id') : $request->user()->branch_id;

        return view('inventory.index', [
            'stocks' => ProductStock::query()->with(['product', 'branch'])
                ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
                ->paginate(25),
            'mutations' => StockMutation::query()
                ->with(['branch', 'product'])
                ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
                ->latest()
                ->limit(20)
                ->get(),
            'branches' => Branch::query()->where('is_active', true)->orderBy('name')->get(),
            'products' => Product::query()->where('type', 'retail')->where('track_stock', true)->where('is_active', true)->orderBy('name')->get(),
            'suppliers' => Supplier::query()->where('is_active', true)->orderBy('name')->get(),
            'selectedBranchId' => $branchId,
        ]);
    }

    public function purchase(Request $request, InventoryService $inventoryService)
    {
        $data = $request->validate([
            'branch_id' => ['required', 'exists:branches,id'],
            'supplier_id' => ['nullable', 'exists:suppliers,id'],
            'purchase_date' => ['required', 'date'],
            'invoice_no' => ['nullable', 'string', 'max:120'],
            'note' => ['nullable', 'string', 'max:1000'],
            'items' => ['required', 'array', 'min:1'],
            'items.*.product_id' => ['required', 'exists:products,id'],
            'items.*.quantity' => ['nullable', 'numeric', 'min:0'],
            'items.*.unit_cost' => ['nullable', 'numeric', 'min:0'],
        ]);

        abort_unless($request->user()->canAccessBranch((int) $data['branch_id']), 403);
        $inventoryService->purchase($data, $request->user());

        return back()->with('status', 'Pembelian berhasil dicatat dan stok bertambah.');
    }

    public function opname(Request $request, InventoryService $inventoryService)
    {
        $data = $request->validate([
            'branch_id' => ['required', 'exists:branches,id'],
            'opname_date' => ['required', 'date'],
            'note' => ['nullable', 'string', 'max:1000'],
            'items' => ['required', 'array', 'min:1'],
            'items.*.product_id' => ['required', 'exists:products,id'],
            'items.*.actual_quantity' => ['nullable', 'numeric', 'min:0'],
        ]);

        abort_unless($request->user()->canAccessBranch((int) $data['branch_id']), 403);
        $inventoryService->opname($data, $request->user());

        return back()->with('status', 'Stock opname diposting dan mutasi stok tercatat.');
    }

    public function adjust(Request $request, InventoryService $inventoryService)
    {
        $data = $request->validate([
            'branch_id' => ['required', 'exists:branches,id'],
            'product_id' => ['required', 'exists:products,id'],
            'quantity' => ['required', 'numeric', 'min:0'],
            'note' => ['nullable', 'string', 'max:1000'],
        ]);

        abort_unless($request->user()->canAccessBranch((int) $data['branch_id']), 403);
        $inventoryService->adjust($data, $request->user());

        return back()->with('status', 'Penyesuaian stok berhasil dicatat.');
    }
}
