<?php

namespace App\Http\Controllers;

use App\Products;
use App\Brands;
use App\Stocks;
use App\Stores;
use App\ProductsCategory;
use App\Measurement_unit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class StocksController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($brand_id, $product_id)
    {
        try {
            $brand_id = Crypt::decrypt($brand_id);
            $product_id = Crypt::decrypt($product_id);

            $product = Products::with(['brand', 'category', 'images', 'stocks'])->where('id_products', $product_id)->firstOrFail();

            return view('stock.index', compact('product', 'brand_id', 'product_id'));
        } catch (DecryptException $e) {
            abort(404);
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($brand_id, $product_id)
    {
        try {
            $brand_id = Crypt::decrypt($brand_id);
            $product_id = Crypt::decrypt($product_id);

            $product = Products::with(['brand', 'category', 'images', 'stocks'])->findOrFail($product_id);
            $stores = Stores::get();

            return view('stock.create', compact('product', 'brand_id', 'product_id', 'stores'));
        } catch (DecryptException $e) {
            abort(404);
        }
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // Validate incoming request
        $validator = Validator::make($request->all(), [
            'products_id' => 'required|exists:products,id_products',
            'store_id' => 'nullable|exists:stores,id_store',
            'stock_batch_number' => 'nullable|string|max:255',
            'stock_purchase_date' => 'required|date',
            'stock_expiry_date' => 'required|date',
            'stock_purchase_qty' => 'required|integer|min:1',
            'stock_purchase_price' => 'required|numeric|min:0',
            'stock_remarks' => 'required|string|max:1000',
            'stock_status' => 'nullable|in:0,1',
        ]);

        // If validation fails, return back with errors
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $stock = new Stocks();
        $stock->products_id = $request->products_id;
        $stock->store_id = $request->store_id;
        $stock->stock_batch_number = $request->stock_batch_number;
        $stock->stock_purchase_date = $request->stock_purchase_date;
        $stock->stock_expiry_date = $request->stock_expiry_date;
        $stock->stock_purchase_qty = $request->stock_purchase_qty;
        $stock->stock_remain_qty = $request->stock_purchase_qty;
        $stock->stock_purchase_price = $request->stock_purchase_price;
        $stock->stock_remarks = $request->stock_remarks;
        $stock->stock_status = $request->stock_status ?? 1;

        $stock->save();

        $product = Products::find($request->products_id);
        if ($product) {
            $product->in_stock += $request->stock_purchase_qty;
            $product->save();
        }

        return redirect()->route('products.stock.list', [
            'brand_id' => Crypt::encrypt($request->brand_id),
            'product_id' => Crypt::encrypt($request->products_id),
        ])->with('alert', 'Stock added successfully!')->with('alert-class', 'success');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Stocks  $stocks
     * @return \Illuminate\Http\Response
     */
    public function show(Stocks $stocks)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Stocks  $stocks
     * @return \Illuminate\Http\Response
     */
    public function edit($id_stock, $product_id)
    {
        try {
            $product_id = Crypt::decrypt($product_id);
            $id_stock = Crypt::decrypt($id_stock);

            $product = Products::with(['brand', 'category', 'images', 'stocks'])->findOrFail($product_id);
            $stock = $product->stocks()->findOrFail($id_stock);

            return view('stock.edit', compact('product', 'stock'));
        } catch (DecryptException $e) {
            abort(404);
        }
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Stocks  $stocks
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id_stock, $product_id)
    {
        try {
            $id_stock = Crypt::decrypt($id_stock);
            $product_id = Crypt::decrypt($product_id);

            $product = Products::where('id_products', $product_id)->firstOrFail();
            $stock = Stocks::where('id_stock', $id_stock)->where('products_id', $product_id)->firstOrFail();

            $request->validate([
                'stock_batch_number' => 'required|string|max:255',
                'stock_purchase_date' => 'required|date',
                'stock_expiry_date' => 'required|date',
            ]);

            $stock->update([
                'stock_batch_number' => $request->stock_batch_number,
                'stock_purchase_date' => $request->stock_purchase_date,
                'stock_expiry_date' => $request->stock_expiry_date,
            ]);

            return redirect()->route('products.stock.list', ['brand_id' => Crypt::encrypt($product->brands_id), 'product_id' => Crypt::encrypt($product->id_products)])
                ->with('alert', 'Stock updated successfully')
                ->with('alert-class', 'success');
        } catch (DecryptException $e) {
            return redirect()->back()->with('alert', 'Failed to decrypt parameters')->with('alert-class', 'danger');
        }
    }

    public function increase($id_stock, $product_id)
    {
        try {
            $id_stock = Crypt::decrypt($id_stock);
            $product_id = Crypt::decrypt($product_id);

            $stock = Stocks::where('id_stock', $id_stock)->where('products_id', $product_id)->firstOrFail();
            $product = Products::findOrFail($product_id);

            return view('stocks.increase', compact('stock', 'product'));
        } catch (DecryptException $e) {
            return redirect()->back()->with('alert', 'Failed to decrypt parameters')->with('alert-class', 'danger');
        }
    }

    // public function increaseStock(Request $request, $id_stock, $product_id)
    // {
    //     try {
    //         $id_stock = Crypt::decrypt($id_stock);
    //         $product_id = Crypt::decrypt($product_id);

    //         $stock = Stocks::where('id_stock', $id_stock)->where('products_id', $product_id)->firstOrFail();
    //         $product = Products::findOrFail($product_id);

    //         $request->validate([
    //             'stock_purchase_qty' => 'required|numeric|min:0',
    //             'stock_type' => 'required|string|in:increase,reverse',
    //         ]);

    //         $stock_purchase_qty = $request->stock_purchase_qty;
    //         $stock_remain_qty = $stock->stock_remain_qty;

    //         if ($request->stock_type == 'increase') {
    //             $stock_remain_qty += $stock_purchase_qty;
    //         } else {
    //             $stock_remain_qty -= $stock_purchase_qty;
    //         }

    //         $stock->update([
    //             'stock_remain_qty' => $stock_remain_qty,
    //             'stock_purchase_qty' => $stock_purchase_qty,
    //             'stock_remarks' => $request->stock_remarks,
    //         ]);

    //         $product->update([
    //             'in_stock' => $stock_remain_qty,
    //         ]);

    //         return redirect()->route('products.stock.list', [
    //             'brand_id' => Crypt::encrypt($product->brands_id), 
    //             'product_id' => Crypt::encrypt($product->id_products)
    //         ])->with('alert', 'Stock updated successfully')->with('alert-class', 'success');
    //     } catch (DecryptException $e) {
    //         return redirect()->back()->with('alert', 'Failed to decrypt parameters')->with('alert-class', 'danger');
    //     }
    // }
    public function increaseStock(Request $request, $id_stock, $product_id)
    {
        try {
            $id_stock = Crypt::decrypt($id_stock);
            $product_id = Crypt::decrypt($product_id);

            $stock = Stocks::where('id_stock', $id_stock)->where('products_id', $product_id)->firstOrFail();
            $product = Products::findOrFail($product_id);

            $request->validate([
                'stock_purchase_qty' => 'required|numeric|min:0',
                'stock_type' => 'required|string|in:increase,reverse',
            ]);

            $stock_purchase_qty = $request->stock_purchase_qty;
            $stock_remain_qty = $stock->stock_remain_qty;

            if ($request->stock_type == 'increase') {
                $stock_remain_qty += $stock_purchase_qty;
            } else {
                $stock_remain_qty -= $stock_purchase_qty;
            }

            $stock->update([
                'stock_remain_qty' => $stock_remain_qty,
                'stock_purchase_qty' => $stock->stock_purchase_qty + ($request->stock_type == 'increase' ? $stock_purchase_qty : -$stock_purchase_qty),
                'stock_remarks' => $request->stock_remarks,
            ]);

            $product->update([
                'in_stock' => $product->in_stock + ($request->stock_type == 'increase' ? $stock_purchase_qty : -$stock_purchase_qty),
            ]);

            return redirect()->route('products.stock.list', [
                'brand_id' => Crypt::encrypt($product->brands_id), 
                'product_id' => Crypt::encrypt($product->id_products)
            ])->with('alert', 'Stock updated successfully')->with('alert-class', 'success');
        } catch (DecryptException $e) {
            return redirect()->back()->with('alert', 'Failed to decrypt parameters')->with('alert-class', 'danger');
        }
    }

    public function damage(Request $request, $id_stock, $product_id)
    {
        try {
            $id_stock = Crypt::decrypt($id_stock);
            $product_id = Crypt::decrypt($product_id);

            $stock = Stocks::where('id_stock', $id_stock)->where('products_id', $product_id)->firstOrFail();
            $product = Products::findOrFail($product_id);

            return view('stocks.damage', compact('stock', 'product'));
        } catch (DecryptException $e) {
            return redirect()->back()->with('alert', 'Failed to decrypt parameters')->with('alert-class', 'danger');
        }
    }

    public function addDamage(Request $request, $id_stock, $product_id)
    {
        try {
            $id_stock = Crypt::decrypt($id_stock);
            $product_id = Crypt::decrypt($product_id);

            $stock = Stocks::where('id_stock', $id_stock)->where('products_id', $product_id)->firstOrFail();
            $product = Products::findOrFail($product_id);

            $request->validate([
                'stock_damage_qty' => 'required|numeric|min:0',
                'stock_damage_date' => 'required|date',
                'stock_remarks' => 'required|string',
            ]);

            $stock_damage_qty = $request->stock_damage_qty;
            $stock_remain_qty = $stock->stock_remain_qty - $stock_damage_qty;

            $stock->update([
                'stock_remain_qty' => $stock_remain_qty,
                'stock_damage_qty' => $stock->stock_damage_qty + $stock_damage_qty,
                'stock_damage_date' => $request->stock_damage_date,
                'stock_remarks' => $request->stock_remarks,
            ]);

            $product->update([
                'in_stock' => $product->in_stock - $stock_damage_qty,
            ]);

            return redirect()->route('products.stock.list', [
                'brand_id' => Crypt::encrypt($product->brands_id), 
                'product_id' => Crypt::encrypt($product->id_products)
            ])->with('alert', 'Stock damage updated successfully')->with('alert-class', 'success');
        } catch (DecryptException $e) {
            return redirect()->back()->with('alert', 'Failed to decrypt parameters')->with('alert-class', 'danger');
        }
    }




    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Stocks  $stocks
     * @return \Illuminate\Http\Response
     */
    public function destroy(Stocks $stocks)
    {
        //
    }
}
