<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\PriceListingSetup;
use App\Models\InventoryJournal;
use App\Models\InventoryCategory;
use App\Models\CompanySettings;
use App\Models\ItemWarehouse;
use App\Models\Warehouse;
use PDF;
use Carbon\Carbon;

class StockValuationController extends Controller
{
    public function index()
    {
        $items = PriceListingSetup::orderBy('code')->get();
        $categories = InventoryCategory::orderBy('name')->get();
        $warehouses = Warehouse::orderBy('description')->get();
        $currentDate = Carbon::now()->format('Y-m-d');

        return view('reports.stock-valuation', compact('items', 'categories', 'warehouses', 'currentDate'));
    }

    public function generate(Request $request)
    {
        $request->validate([
            'date_from' => 'required|date',
            'date_to'   => 'required|date|after_or_equal:date_from',
        ]);

        $itemFrom    = $request->item_from;
        $itemTo      = $request->item_to;
        $dateFrom    = $request->date_from;
        $dateTo      = $request->date_to;
        $groupId     = $request->group_id;
        $warehouseId = $request->warehouse_id;
        $company     = CompanySettings::first();

        $items       = PriceListingSetup::orderBy('code')->get();
        $categories  = InventoryCategory::orderBy('name')->get();
        $warehouses  = Warehouse::orderBy('description')->get();

        // Build query for items
        $query = PriceListingSetup::with(['category', 'warehouse']);

        if ($itemFrom && $itemTo) {
            $query->whereBetween('code', [$itemFrom, $itemTo]);
        }

        if ($groupId) {
            $query->where('category_id', $groupId);
        }

        if ($warehouseId) {
            $query->where('warehouse_id', $warehouseId);
        }

        $selectedItems = $query->orderBy('code')->get();

        $stockData = [];
        $grandTotalValue = 0;

        foreach ($selectedItems as $item) {
            // ✅ Get actual stock from itemwarehouse
            $availableQuantity = ItemWarehouse::where('item_id', $item->id)
                ->when($warehouseId, function ($q) use ($warehouseId) {
                    $q->where('warehouse_id', $warehouseId);
                })
                ->sum('quantity');

            $unitCost   = $item->cost ?? 0;
            $totalValue = $unitCost * $availableQuantity;
            $grandTotalValue += $totalValue;

            $category  = $item->category;
            $warehouse = $item->warehouse;

            if ($availableQuantity > 0) {
                $stockData[] = [
                    'item'                => $item,
                    'warehouse'           => $warehouse,
                    'category'            => $category,
                    'available_quantity'  => $availableQuantity,
                    'unit_cost'           => $unitCost,
                    'total_value'         => $totalValue,
                ];
            }
        }

        return view('reports.stock-valuation', compact(
            'stockData',
            'grandTotalValue',
            'itemFrom',
            'itemTo',
            'dateFrom',
            'dateTo',
            'groupId',
            'warehouseId',
            'items',
            'categories',
            'warehouses',
            'company'
        ));
    }

    public function downloadPdf(Request $request)
    {
        $request->validate([
            'date_from' => 'required|date',
            'date_to'   => 'required|date|after_or_equal:date_from',
        ]);

        $itemFrom    = $request->item_from;
        $itemTo      = $request->item_to;
        $dateFrom    = $request->date_from;
        $dateTo      = $request->date_to;
        $groupId     = $request->group_id;
        $warehouseId = $request->warehouse_id;
        $company     = CompanySettings::first();

        // Build query for items
        $query = PriceListingSetup::with(['category', 'warehouse']);

        if ($itemFrom && $itemTo) {
            $query->whereBetween('code', [$itemFrom, $itemTo]);
        }

        if ($groupId) {
            $query->where('category_id', $groupId);
        }

        if ($warehouseId) {
            $query->where('warehouse_id', $warehouseId);
        }

        $selectedItems = $query->orderBy('code')->get();

        $stockData = [];
        $grandTotalValue = 0;

        foreach ($selectedItems as $item) {
            // ✅ Get actual stock from itemwarehouse
            $availableQuantity = ItemWarehouse::where('item_id', $item->id)
                ->when($warehouseId, function ($q) use ($warehouseId) {
                    $q->where('warehouse_id', $warehouseId);
                })
                ->sum('quantity');

            $unitCost   = $item->cost ?? 0;
            $totalValue = $unitCost * $availableQuantity;
            $grandTotalValue += $totalValue;

            $category  = $item->category;
            $warehouse = $item->warehouse;

            if ($availableQuantity > 0) {
                $stockData[] = [
                    'item'                => $item,
                    'warehouse'           => $warehouse,
                    'category'            => $category,
                    'available_quantity'  => $availableQuantity,
                    'unit_cost'           => $unitCost,
                    'total_value'         => $totalValue,
                ];
            }
        }

        $pdf = PDF::loadView('reports.stock-valuation-pdf', compact(
            'stockData',
            'grandTotalValue',
            'dateFrom',
            'dateTo',
            'itemFrom',
            'itemTo',
            'groupId',
            'warehouseId',
            'company'
        ));

        return $pdf->download('stock-valuation-report.pdf');
    }
}
