<?php

namespace App\Http\Controllers;

use App\Models\WarehouseBin;
use App\Models\Warehouse;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class WarehouseBinController extends Controller
{
    public function index()
    {
        return view('warehouse_bins.index');
    }

    public function create()
    {
        $warehouses = Warehouse::where('is_active', true)->get();
        return view('warehouse_bins.create', compact('warehouses'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'code' => 'required|string|max:255',
            'warehouse_id' => 'required|exists:warehouses,id',
            'type' => 'required|in:receipt,general,dispatch,quality,damaged',
            'is_active' => 'boolean'
        ]);

        WarehouseBin::create($request->all());

        return redirect()->route('warehouse-bins.index')
            ->with('success', 'Warehouse bin created successfully.');
    }

    public function show(WarehouseBin $warehouseBin)
    {
        $warehouseBin->load(['warehouse', 'stockBalances', 'stockLedgerEntries']);
        return view('warehouse_bins.show', compact('warehouseBin'));
    }

    public function edit(WarehouseBin $warehouseBin)
    {
        $warehouses = Warehouse::where('is_active', true)->get();
        return view('warehouse_bins.edit', compact('warehouseBin', 'warehouses'));
    }

    public function update(Request $request, WarehouseBin $warehouseBin)
    {
        $request->validate([
            'code' => 'required|string|max:255',
            'warehouse_id' => 'required|exists:warehouses,id',
            'type' => 'required|in:receipt,general,dispatch,quality,damaged',
            'is_active' => 'boolean'
        ]);

        $warehouseBin->update($request->all());

        return redirect()->route('warehouse-bins.index')
            ->with('success', 'Warehouse bin updated successfully.');
    }

    public function destroy(WarehouseBin $warehouseBin)
    {
        // Check if bin has stock balances or transfers
        if ($warehouseBin->stockBalances()->exists() ||
            $warehouseBin->fromTransfers()->exists() ||
            $warehouseBin->toTransfers()->exists()) {
            return redirect()->route('warehouse-bins.index')
                ->with('error', 'Cannot delete bin with associated stock or transfers.');
        }

        $warehouseBin->delete();

        return redirect()->route('warehouse-bins.index')
            ->with('success', 'Warehouse bin deleted successfully.');
    }

    public function getData()
    {
        $bins = WarehouseBin::with(['warehouse'])
            ->orderBy('warehouse_id')
            ->orderBy('code')
            ->get();

        return DataTables::of($bins)
            ->addColumn('warehouse_name', function ($bin) {
                return $bin->warehouse->name ?? 'N/A';
            })
            ->addColumn('warehouse_code', function ($bin) {
                return $bin->warehouse->code ?? 'N/A';
            })
            ->addColumn('type_label', function ($bin) {
                $labels = [
                    'receipt' => 'Receipt',
                    'general' => 'General',
                    'dispatch' => 'Dispatch',
                    'quality' => 'Quality',
                    'damaged' => 'Damaged'
                ];
                return $labels[$bin->type] ?? $bin->type;
            })
            ->addColumn('status_badge', function ($bin) {
                return $bin->status_badge;
            })
            ->addColumn('type_badge', function ($bin) {
                return $bin->type_badge;
            })
            ->addColumn('full_code', function ($bin) {
                return $bin->full_code;
            })
            ->addColumn('stock_count', function ($bin) {
                return $bin->stockBalances()->count();
            })
            ->addColumn('actions', function ($bin) {
                $actions = '<div class="btn-group" role="group">';
                $actions .= '<a href="' . route('warehouse-bins.show', $bin->id) . '" class="btn btn-sm btn-info">View</a>';
                $actions .= '<a href="' . route('warehouse-bins.edit', $bin->id) . '" class="btn btn-sm btn-warning">Edit</a>';
                $actions .= '<form method="POST" action="' . route('warehouse-bins.destroy', $bin->id) . '" style="display:inline;">';
                $actions .= csrf_field() . method_field('DELETE');
                $actions .= '<button type="submit" class="btn btn-sm btn-danger" onclick="return confirm(\'Are you sure you want to delete this bin?\')">Delete</button>';
                $actions .= '</form>';
                $actions .= '</div>';
                return $actions;
            })
            ->rawColumns(['status_badge', 'type_badge', 'actions'])
            ->make(true);
    }

    public function toggleActive(WarehouseBin $warehouseBin)
    {
        $warehouseBin->update(['is_active' => !$warehouseBin->is_active]);

        $status = $warehouseBin->is_active ? 'activated' : 'deactivated';

        return redirect()->route('warehouse-bins.index')
            ->with('success', "Warehouse bin {$status} successfully.");
    }
}
