<?php

namespace App\Http\Controllers;

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

class WarehouseController extends Controller
{
    public function index()
    {
        $warehouses = Warehouse::where('company_id', Auth::user()->current_company_id)
            ->withCount(['stockBatches as active_items_count' => function($query) {
                $query->where('remaining_qty', '>', 0);
            }])
            ->get();

        return view('inventory.warehouses.index', compact('warehouses'));
    }

    public function create()
    {
        return view('inventory.warehouses.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:warehouses,code',
            'address' => 'nullable|string',
        ]);

        return DB::transaction(function () use ($request) {
            $companyId = Auth::user()->current_company_id;
            
            // Check if this is the first warehouse
            $isFirst = Warehouse::where('company_id', $companyId)->count() === 0;
            $setAsPrimary = $isFirst || $request->has('is_primary');

            // If we are setting this as primary, demote all others first
            if ($setAsPrimary) {
                Warehouse::where('company_id', $companyId)->update(['is_primary' => false]);
            }

            Warehouse::create([
                'company_id' => $companyId,
                'name' => $request->name,
                'code' => strtoupper($request->code),
                'address' => $request->address,
                'is_primary' => $setAsPrimary,
                'created_by' => Auth::id(),
            ]);

            return redirect()->route('inventory.warehouses.index')
                ->with('success', 'Warehouse location established successfully.');
        });
    }

    public function edit($id)
    {
        $warehouse = Warehouse::where('company_id', Auth::user()->current_company_id)->findOrFail($id);
        return view('inventory.warehouses.edit', compact('warehouse'));
    }

    public function update(Request $request, $id)
    {
        $warehouse = Warehouse::where('company_id', Auth::user()->current_company_id)->findOrFail($id);

        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:warehouses,code,' . $id,
        ]);

        return DB::transaction(function () use ($request, $warehouse) {
            $companyId = Auth::user()->current_company_id;

            // Logic: If user is making THIS one primary, demote the others.
            if ($request->has('is_primary')) {
                Warehouse::where('company_id', $companyId)
                    ->where('id', '!=', $warehouse->id)
                    ->update(['is_primary' => false]);
            }

            $warehouse->update([
                'name' => $request->name,
                'code' => strtoupper($request->code),
                'address' => $request->address,
                'is_primary' => $request->has('is_primary') || $warehouse->is_primary, 
            ]);

            return redirect()->route('inventory.warehouses.index')
                ->with('success', 'Location details updated.');
        });
    }
    
    
    /**
     * Remove the specified warehouse from storage after safety checks.
     */
    public function destroy($id)
    {
        $companyId = Auth::user()->current_company_id;
        $warehouse = Warehouse::where('company_id', $companyId)->findOrFail($id);

        // 1. Check for Active Stock Batches (Items currently on shelves)
        $hasActiveStock = \App\Models\StockBatch::where('warehouse_id', $id)
            ->where('remaining_qty', '>', 0)
            ->exists();

        if ($hasActiveStock) {
            return back()->with('error', "Cannot delete '{$warehouse->name}': It currently contains active stock. Please transfer or adjust stock to zero first.");
        }

        // 2. Check for Transaction History (Audit Trail Integrity)
        $hasHistory = \App\Models\StockMovement::where('warehouse_id', $id)->exists();

        if ($hasHistory) {
            return back()->with('error', "Cannot delete '{$warehouse->name}': This location has historical transaction records. You should rename it to '(DEPRECATED)' instead of deleting to preserve audit trails.");
        }

        // 3. Prevent deleting the only/primary warehouse
        if ($warehouse->is_primary) {
            return back()->with('error', "Cannot delete the Primary Warehouse. Assign another location as Primary first.");
        }

        $warehouse->delete();

        return redirect()->route('inventory.warehouses.index')
            ->with('success', 'Storage location removed successfully.');
    }
    
}