<?php

namespace App\Http\Controllers\Report;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\ProductStock;
use App\Models\ProductPrice;
use App\Models\Branch;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;

class ProductListReportController extends Controller
{
    public function __construct()
    {
        $this->middleware(['permission:item.index'])->only('index', 'exportPdf');
    }

    public function index(Request $request)
    {
        $title = 'product_list_report';
        $branches = Branch::all();
        $branchId = $request->get('branch_id');

        $branch = $branchId ? Branch::find($branchId) : null;

        // Build query based on branch filter
        if ($branchId) {
            // Get only products that have stock in the selected branch
            $productIds = ProductStock::where('branch_id', $branchId)
                ->pluck('product_id')
                ->unique();

            $productsQuery = Product::with(['brand', 'category'])
                ->whereIn('id', $productIds);
        } else {
            // Get all products
            $productsQuery = Product::with(['brand', 'category']);
        }

        $products = $productsQuery->get()
            ->map(function($product) use ($branchId) {
                // Get stock for selected branch
                if ($branchId) {
                    // Filter by specific branch
                    $stock = ProductStock::where('product_id', $product->id)
                        ->where('branch_id', $branchId)
                        ->first();

                    $price = ProductPrice::where('product_id', $product->id)
                        ->where('branch_id', $branchId)
                        ->orderBy('effective_date', 'desc')
                        ->first();
                } else {
                    // If no branch selected, get first available stock/price
                    $stock = ProductStock::where('product_id', $product->id)
                        ->first();

                    $price = ProductPrice::where('product_id', $product->id)
                        ->orderBy('effective_date', 'desc')
                        ->first();
                }

                $product->stock_quantity = $stock ? $stock->quantity : 0;
                $product->rack = $stock ? $stock->rack : '-';
                $product->purchase_price = $price ? $price->purchase_price : 0;
                $product->selling_price = $price ? $price->selling_price : 0;
                $product->asset = $product->stock_quantity * $product->purchase_price;
                // min_stock already exists in product model, no need to reassign

                return $product;
            });

        return view('report.product-list.index', compact(
            'title',
            'branches',
            'branchId',
            'branch',
            'products'
        ));
    }

    public function exportPdf(Request $request)
    {
        $branchId = $request->get('branch_id');
        $branch = $branchId ? Branch::find($branchId) : null;

        // Build query based on branch filter
        if ($branchId) {
            // Get only products that have stock in the selected branch
            $productIds = ProductStock::where('branch_id', $branchId)
                ->pluck('product_id')
                ->unique();

            $productsQuery = Product::with(['brand', 'category'])
                ->whereIn('id', $productIds);
        } else {
            // Get all products
            $productsQuery = Product::with(['brand', 'category']);
        }

        $products = $productsQuery->get()
            ->map(function($product) use ($branchId) {
                // Get stock for selected branch
                if ($branchId) {
                    // Filter by specific branch
                    $stock = ProductStock::where('product_id', $product->id)
                        ->where('branch_id', $branchId)
                        ->first();

                    $price = ProductPrice::where('product_id', $product->id)
                        ->where('branch_id', $branchId)
                        ->orderBy('effective_date', 'desc')
                        ->first();
                } else {
                    // If no branch selected, get first available stock/price
                    $stock = ProductStock::where('product_id', $product->id)
                        ->first();

                    $price = ProductPrice::where('product_id', $product->id)
                        ->orderBy('effective_date', 'desc')
                        ->first();
                }

                $product->code = 'B-' . str_pad($product->id, 4, '0', STR_PAD_LEFT);
                $product->barcode = $product->barcode;
                $product->stock_quantity = $stock ? $stock->quantity : 0;
                $product->rack = $stock ? $stock->rack : '-';
                $product->purchase_price = $price ? $price->purchase_price : 0;
                $product->selling_price = $price ? $price->selling_price : 0;
                $product->asset = $product->stock_quantity * $product->purchase_price;
                // min_stock already exists in product model, no need to reassign

                return $product;
            });

        $pdf = Pdf::loadView('report.product-list.pdf', compact(
            'branch',
            'products'
        ))->setPaper('a4', 'landscape');

        return $pdf->stream('Daftar-Item-' . date('Ymd') . '.pdf');
    }
}
