<?php

namespace App\Http\Controllers;

use App\Models\Accesories;
use App\Models\stockinsummary;
use App\Models\Stockout;
use App\Models\Stockoutdetails;
use Illuminate\Http\Request;

class StockoutController extends Controller
{
    // List all stock-in entries
    public function index()
    {
        $title = 'Stock Out List';
        $stockOut = Stockout::all();  // Fetch all stock-in records
        return view('backend.pages.stockOut.index', compact('stockOut', 'title'));  // Return the stock-in list view
    }
    public function getUnitByName($name)
    {
        // Fetch the accessory by name
        $accessory = Accesories::where('name', $name)->first();

        if ($accessory) {
            return response()->json([
                'unit' => $accessory->unit,
            ]);
        }

        return response()->json([
            'unit' => null,
        ]);
    }
    // Show the form to create a new stock-in entry
    public function create()
    {
        return view('backend.pages.stockOut.create');  // Return the create form view
    }

    public function store(Request $request)
    {
        $request->validate([
            'description.*' => 'required|string',
            'in_quantity.*' => 'required|integer|min:1',
            'accessory_id.*' => 'required|exists:accesories,id',
        ]);
        $stock = new stockOut();
        $stock->date = today();

        $stock->save();
        foreach ($request->input('description') as $key => $description) {
            $accessoryId = $request->input('accessory_id')[$key];
            $quantity = $request->input('in_quantity')[$key];

            $stockOut = new Stockoutdetails();
            $stockOut->aceesories_id = $accessoryId;
            $stockOut->stock_ins_id = $stock->id;
            $stockOut->in_quantity = $quantity;
            $stockOut->description = $description;
            $stockOut->save();


            $stockSummary = stockinsummary::where('product_id', $accessoryId)
                ->first();

            if ($stockSummary) {
                $stockSummary->quantity -= $quantity;
                $stockSummary->save();
            } 
        }

        return redirect()->route('stockOut.list')->with('success', 'Stock-out created successfully.');
    }


    // Show the details of a specific stock-in entry
    public function show($id)
    {
        $stockIn  = stockOut::findOrFail($id);  // Find the stock-in record by ID
        return view('backend.pages.stockOut.show', compact('stockIn '));  // Return the show view
    }

    // Show the form to edit a specific stock-in entry
    public function edit($id)
    {
        $stockIn  = stockOut::findOrFail($id);  // Find the stock-in record by ID
        return view('backend.pages.stockOut.edit', compact('stockIn'));  // Return the edit form view
    }



    public function update(Request $request, $id)
    {
        $stockOut = stockOut::findOrFail($id);
        $existingDetailIds = $request->detail_id ?? []; // Array of submitted detail IDs

        // ✅ Delete details that were removed from the form
        stockOutdetails::where('stock_ins_id', $stockOut->id)
            ->whereNotIn('id', $existingDetailIds)
            ->delete();
        foreach ($request->accessory_id as $key => $accessoryId) {
            $description = $request->description[$key];
            $in_quantity = $request->in_quantity[$key];


            // Check if this detail already exists
            $detail = stockOutdetails::where('id', $request->detail_id[$key])->first();


            if ($detail) {
                $detail->description = $description;
                $detail->in_quantity = $in_quantity;
            } else {
                $detail = new stockOutdetails();
                $detail->stock_ins_id = $stockOut->id;
                $detail->aceesories_id = $accessoryId;
                $detail->description = $description;
                $detail->in_quantity = $in_quantity;
            }
            $stockSummary = stockinsummary::where('product_id', $accessoryId)
                ->first();

            if ($stockSummary) {
                $stockSummary->quantity -= $request->old_quantity[$key]; // subtract old
                $stockSummary->quantity += $in_quantity;                 // add new                
                $stockSummary->save();
            } else {
                $newStockSummary = new stockinsummary();
                $newStockSummary->product_id = $accessoryId;
                $newStockSummary->quantity = $in_quantity;
                $newStockSummary->save();
            }
            $detail->save();
        }

        return redirect()->route('stockOut.list')->with('success', 'Stock-out details updated successfully.');
    }


    // Delete a specific stock-in entry
    public function delete($id)
    {
        $stockOut = stockOut::findOrFail($id);  // Find the stock-in record by ID
        $stockOut->delete();  // Delete the stock-in record

        return redirect()->route('stockOut.list')->with('success', 'Stock-out deleted successfully.');  // Redirect with success message
    }

    // Optionally, a report or other action related to stock-in can be added
    public function report()
    {
        // Logic for generating a stock-in report
        return view('backend.pages.stockOut.report');  // Return a report view
    }
}
