<?php

namespace App\Http\Controllers\Stocks;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\VoucherType;
use Illuminate\Http\Request;

class OpeningStockController extends Controller
{
    protected  $mainFolderName = 'stocks';

    public function index(Request $request)
    {
        \Session::forget('stock_in_products_cart');


        if ($request->ajax()) {

            $StockInVoucher = VoucherType::select(['default_price_type'])->where(['code' => 'STOCK_IN'])->first();

            if ($StockInVoucher->default_price_type == 'MRP') {
                $productPrice = 'product_prices.mrp as mrp';
            } elseif ($StockInVoucher->default_price_type == 'Purchase Price') {
                $productPrice = 'product_prices.purchase_price as mrp';
            } elseif ($StockInVoucher->default_price_type == 'WholeSale Price') {
                $productPrice = 'product_prices.wholesale_price as mrp';
            } elseif ($StockInVoucher->default_price_type == 'Discounted/Sale Price(DP)') {
                $productPrice = 'product_prices.sale_price as mrp';
            } elseif ($StockInVoucher->default_price_type == 'Min. Sale Price') {
                $productPrice = 'product_prices.min_sale_price as mrp';
            } elseif ($StockInVoucher->default_price_type == 'Manufacturing Cost') {
                $productPrice = 'product_prices.mfg_cost as mrp';
            }

            $data = Product::with('getProductPrimaryUnit')
                ->select([
                    'products.id', 'products.name',
                    'product_prices.opening_stock_pack',
                    'product_prices.id as product_price_id', 
                    'product_prices.batch','product_prices.exp_date', 
                    'products.primary_unit_id', $productPrice
                ])
                ->leftJoin('product_prices', 'product_prices.product_id', '=', 'products.id')
                ->where('product_prices.opening_stock_pack', '>', 0);
            $sort_by      = $request->get('sortby') ?? 100;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('products.name', 'LIKE', '%' . $search_query . '%');
            })
                ->orderBy('id', 'desc')
                ->paginate($sort_by);

            return view($this->mainFolderName . '.opening-stock.table', compact('data', 'sort_by'));
        } else {
            return view($this->mainFolderName . '.opening-stock.index');
        }
    }

    public function processToStockIn(Request $request)
    {
        $ids = $request->input('ids');

        $StockInVoucher = VoucherType::select(['default_price_type'])->where(['code' => 'STOCK_IN'])->first();

        if ($StockInVoucher->default_price_type == 'MRP') {
            $productPrice = 'product_prices.mrp as mrp';
        } elseif ($StockInVoucher->default_price_type == 'Purchase Price') {
            $productPrice = 'product_prices.purchase_price as mrp';
        } elseif ($StockInVoucher->default_price_type == 'WholeSale Price') {
            $productPrice = 'product_prices.wholesale_price as mrp';
        } elseif ($StockInVoucher->default_price_type == 'Discounted/Sale Price(DP)') {
            $productPrice = 'product_prices.sale_price as mrp';
        } elseif ($StockInVoucher->default_price_type == 'Min. Sale Price') {
            $productPrice = 'product_prices.min_sale_price as mrp';
        } elseif ($StockInVoucher->default_price_type == 'Manufacturing Cost') {
            $productPrice = 'product_prices.mfg_cost as mrp';
        }

        $products = Product::with('getTaxMaster')
            ->select(
                [
                    'products.id', 'products.name',
                    'products.hsncode', 'product_brands.name as brand',
                    'tax_masters.name as tax', 'product_prices.batch as batch',
                    'product_prices.opening_stock_pack',
                    'product_prices.id as product_price_id',
                    $productPrice
                ]
            )
            ->leftJoin('product_prices', 'product_prices.product_id', '=', 'products.id')
            ->leftJoin('product_brands', 'product_brands.id', 'products.brand_id')
            ->leftJoin('tax_masters', 'tax_masters.id', 'products.tax_slab_id')
            ->whereIN('product_prices.id', $ids)->get();
        // dd($products);

        $data            = [];
        $customer        =  '';
        $doctor          = '';
        $amount = 0;
        $pack_qty_in_amount = 0;


        $data['moment_type']            = 'Opening' ?? '';
        $data['date']                   = date('d-m-Y');
        $data['discount_type']          = 'FLAT';
        $data['invoice_date']           = date('d-m-Y');
        $data['payment_mode_id']        = '';
        $data['special_discount']       = 0;
        $data['types']                  = "opening";

        foreach ($products as $key => $value) {


            $pack_qty_in_amount =  $value->opening_stock_pack * $value->mrp;

            $amount += $pack_qty_in_amount;

            $tax_per = isset($value->tax) && $value->tax != 'Tax Free' ? preg_replace('/[^0-9]/', '', $value->tax ?? 0,) : 0;

            $tax  = (($tax_per ?? 0) / 100) * $pack_qty_in_amount;

            $data['products'][] = array(
                'batch'          => $value->batch,
                'price_id'       => $value->product_price_id ?? '',
                'product_id'     => $value->id ?? '',
                'product'        => $value->name ?? '',
                'hsncode'        => $value->hsncode ?? '',
                'product_price'  => $value->mrp ?? '0',
                'flat_discount'  =>  '0',
                'per_discount'   =>  '0',
                'product_detail' => $value->item_details ?? '',
                'amount'         => $pack_qty_in_amount ?? '0',
                'main_qty'       => $value->opening_stock_pack ?? '0',
                'loose_qty'      =>  '0',
                'free_qty'       =>  '0',
                'tax_per'        => $tax_per,
                'tax_flat'       => $tax ?? 0,
                'product_mrp'    => convertDecimelPoint($value->mrp) ?? '',
                'product_basic'  => convertDecimelPoint($value->mrp) ?? '',
                'expiry_date'    => $request->expiry_date ? date('M-Y', strtotime($request->expiry_date)) : '',
            );
        }

        $data['amount']                 =  $amount;
        $data['amount_recieved']        =  0;
        $data['due_balance_amount']     =  $amount;

        \Session::put('stock_in_products_cart', $data);

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => []
        ]);
    }
}
