<?php

namespace App\Http\Controllers;

use App\Models\StockBalance;
use App\Models\Item;
use App\Models\Warehouse;
use App\Models\WarehouseBin;
use Illuminate\Http\Request;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;
use Yajra\DataTables\Facades\DataTables;

class StockController extends Controller
{
    // public function index(Request $request): View
    // {
    //     $items = Item::where('is_active', true)->orderBy('name')->get();
    //     $warehouses = Warehouse::where('is_active', true)->orderBy('name')->get();
    //     $bins = WarehouseBin::where('is_active', true)->orderBy('code')->get();

    //     return view('stocks.index', compact('items', 'warehouses', 'bins'));
    // }

    public function index(Request $request): View
    {
        $type    = $request->input('type', 'FG');
        $chartId = $type === 'FG' ? 53 : 52; // 53=FG, 52=RM

        $stocks = \App\Models\Stock::with(['account', 'warehouse'])
            ->whereHas('account', function ($q) use ($chartId) {
                $q->where('model_type', 'Item')
                ->where('is_shop_item', 0)
                ->where('chart_of_account_id', $chartId);
            })
            ->get();

        $totalItems = $stocks->count();
        $inStock    = $stocks->where('quantity', '>', 10)->count();
        $lowStock   = $stocks->filter(fn($s) => $s->quantity > 0 && $s->quantity <= ($s->account->reorder_level ?? 10))->count();
        $outOfStock = $stocks->where('quantity', '<=', 0)->count();

        return view('stocks.index', compact(
            'stocks', 'totalItems', 'inStock', 'lowStock', 'outOfStock', 'type'
        ));
    }


    // public function getData(Request $request): JsonResponse
    // {
    //     $query = StockBalance::query()
    //         ->with(['item', 'warehouse', 'bin'])
    //         ->select('stock_balances.*');

    //     // Apply filters
    //     if ($request->filled('item_id')) {
    //         $query->where('item_id', $request->item_id);
    //     }

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

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

    //     if ($request->filled('stock_status')) {
    //         switch ($request->stock_status) {
    //             case 'in_stock':
    //                 $query->where('on_hand_qty', '>', 0);
    //                 break;
    //             case 'out_of_stock':
    //                 $query->where('on_hand_qty', '<=', 0);
    //                 break;
    //             case 'low_stock':
    //                 $query->where('on_hand_qty', '<=', 10);
    //                 break;
    //         }
    //     }

    //     return DataTables::of($query)
    //         ->addColumn('item_name', function (StockBalance $stock) {
    //             return $stock->item->name ?? 'N/A';
    //         })
    //         ->addColumn('item_sku', function (StockBalance $stock) {
    //             return $stock->item->sku ?? 'N/A';
    //         })
    //         ->addColumn('warehouse_name', function (StockBalance $stock) {
    //             return $stock->warehouse->name ?? 'N/A';
    //         })
    //         ->addColumn('bin_name', function (StockBalance $stock) {
    //             return $stock->bin->code ?? 'N/A';
    //         })
    //         ->editColumn('on_hand_qty', function (StockBalance $stock) {
    //             return number_format($stock->on_hand_qty, 2);
    //         })
    //         ->editColumn('reserved_qty', function (StockBalance $stock) {
    //             return number_format($stock->reserved_qty, 2);
    //         })
    //         ->editColumn('available_qty', function (StockBalance $stock) {
    //             return number_format($stock->available_qty, 2);
    //         })
    //         ->editColumn('unit_cost_avg', function (StockBalance $stock) {
    //             return format_currency($stock->unit_cost_avg);
    //         })
    //         ->editColumn('total_value', function (StockBalance $stock) {
    //             return format_currency($stock->total_value);
    //         })
    //         ->addColumn('stock_status', function (StockBalance $stock) {
    //             if ($stock->on_hand_qty <= 0) {
    //                 return '<span class="badge bg-danger">Out of Stock</span>';
    //             } elseif ($stock->on_hand_qty <= 10) {
    //                 return '<span class="badge bg-warning">Low Stock</span>';
    //             } else {
    //                 return '<span class="badge bg-success">In Stock</span>';
    //             }
    //         })
    //         ->addColumn('actions', function (StockBalance $stock) {
    //             return '<div class="d-flex gap-2">
    //                 <a href="' . route('stocks.show', $stock) . '" class="btn btn-sm btn-outline-primary" title="View Details">
    //                     <i class="fas fa-eye"></i>
    //                 </a>
    //             </div>';
    //         })
    //         ->rawColumns(['stock_status', 'actions'])
    //         ->toJson();
    // }

    public function getData(Request $request): JsonResponse
    {
        $type        = $request->input('type', 'FG');
        $chartId     = $type === 'FG' ? 53 : 52;
        $stockFilter = $request->input('stock_filter', 'all');

        $query = \App\Models\Stock::with(['account.uom', 'warehouse'])
            ->whereHas('account', function ($q) use ($chartId) {
                $q->where('model_type', 'Item')
                ->where('is_shop_item', 0)
                ->where('chart_of_account_id', $chartId);
            });

        // Apply stock filter
        switch ($stockFilter) {
            case 'in_stock':
                $query->whereHas('account', fn($q) => $q->whereRaw('stocks.quantity > COALESCE(accounts.reorder_level, 10)'));
                break;
            case 'low_stock':
                $query->whereHas('account', fn($q) => $q->whereRaw('stocks.quantity > 0 AND stocks.quantity <= COALESCE(accounts.reorder_level, 10)'));
                break;
            case 'out_of_stock':
                $query->where('quantity', '<=', 0);
                break;
        }

        return DataTables::of($query)
            ->addColumn('item_name', fn($s) => $s->account->name ?? 'N/A')
            ->addColumn('item_code', fn($s) => $s->account->code ?? 'N/A')
            ->addColumn('item_sku',  fn($s) => $s->account->sku  ?? 'N/A')
            ->addColumn('warehouse_name', fn($s) => $s->warehouse->name ?? 'N/A')
            ->addColumn('size', function ($s) {
                if ($s->length) {
                        $unit = $s->account && $s->account->uom ? $s->account->uom->name : '';
                        return number_format($s->length, 2) . ' ' . $unit;
                    }
                    // If no length, show just UOM name (for RM like plastic dana, raw copper)
                    if ($s->account && $s->account->uom) {
                        return $s->account->uom->name;
                    }
                    return 'N/A';
                // $unit = $s->account && $s->account->uom ? $s->account->uom->name : '';
                // return $s->length ? number_format($s->length, 2) . ' ' . $unit : 'N/A';
            })
            ->addColumn('bin_name',  fn($s) => '-')
            ->addColumn('lot_no',    fn($s) => '-')
            ->addColumn('on_hand_qty', fn($s) => number_format($s->quantity, 2))
            ->addColumn('reserved_qty',  fn($s) => '-')
            ->addColumn('available_qty', fn($s) => number_format($s->quantity, 2))
            ->addColumn('unit_cost_avg', fn($s) => $s->account->weighted_average_price
                ? 'Rs ' . number_format($s->account->weighted_average_price, 2) : '-')
            ->addColumn('total_value', fn($s) => $s->account->weighted_average_price
                ? 'Rs ' . number_format($s->quantity * $s->account->weighted_average_price, 2) : '-')
            ->addColumn('stock_status', function ($s) {
                $reorderLevel = $s->account->reorder_level ?? 10;
                if ($s->quantity <= 0)               return '<span class="badge bg-danger">Out of Stock</span>';
                if ($s->quantity <= $reorderLevel)   return '<span class="badge bg-warning text-dark">Low Stock</span>';
                return '<span class="badge bg-success">In Stock</span>';
            })
            ->addColumn('actions', fn($s) => '
                <a href="' . route('warehouses.stock-history-finished-goods', [
                    'item_id'      => $s->account_id,
                    'warehouse_id' => $s->warehouse_id
                ]) . '" class="btn btn-sm btn-outline-primary">
                    <i class="fas fa-history me-1"></i>History
                </a>')
            ->rawColumns(['stock_status', 'actions'])
            ->make(true);
    }

    public function show(StockBalance $stock): View
    {
        $stock->load(['item', 'warehouse', 'bin']);

        // Get recent stock movements
        $recentMovements = \App\Models\StockLedger::where('item_id', $stock->item_id)
            ->where('bin_id', $stock->bin_id)
            ->orderBy('occurred_at', 'desc')
            ->limit(20)
            ->get();

        return view('stocks.show', compact('stock', 'recentMovements'));
    }

    public function export(Request $request)
    {
        // Placeholder for export functionality
        return response()->json(['message' => 'Export functionality coming soon']);
    }
}
