<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\items;

class itemsController extends Controller
{
    public function index()
    {
        $items = Items::orderBy("id", "desc")->get();
        return response()->json($items);
    }

    public function searchbox(Request $request)
    {
        $query = Items::query();

        if ($request->has('search')) {
            $search = $request->input('search');
            $query->where('bar_code', 'LIKE', "%$search%")
                ->orWhere('item_name', 'LIKE', "%$search%");
        }

        $items = $query->orderBy("id", "desc")->limit(10)->get();

        return response()->json($items);
    }


    public function store(Request $request)
    {
        // Validate the incoming request data
        $validatedData = $request->validate([
            'item_category_id' => 'required|exists:item_categories,id',
            'bar_code' => 'nullable|unique:items,bar_code', // Can be null, will be assigned if missing
            'item_name' => 'required|string',
            're_order_level' => 'nullable|numeric',
            'is_vat_item' => 'nullable|boolean',
            'is_sscl_item' => 'nullable|boolean',
        ]);

        // If bar_code is null, assign a temporary placeholder (will update after creation)
        $bar_code = $validatedData['bar_code'] ?? null;

        // Create the item with a default bar_code value
        $item = items::create([
            'item_category_id' => $validatedData['item_category_id'],
            'bar_code' => $bar_code ?: 'TEMP', // Temporary value to prevent SQL error
            'item_name' => $validatedData['item_name'],
            're_order_level' => $validatedData['re_order_level'] ?? null,
            'is_vat_item' => $validatedData['is_vat_item'] ?? false,
            'is_sscl_item' => $validatedData['is_sscl_item'] ?? false,
        ]);

        // If bar_code was initially null, assign the item's ID to it
        if (!$bar_code) {
            $item->bar_code = $item->id; // Assign the ID as bar_code
            $item->save(); // Update bar_code in DB
        }

        // Return a response
        return response()->json([
            'message' => 'Item created successfully',
            'item' => $item,
        ], 201);
    }

    public function update(Request $request, $id)
    {
        $item = items::find($id);
        $item->item_category_id = $request->item_category_id;
        $item->bar_code = $request->bar_code;
        $item->item_name = $request->item_name;
        $item->re_order_level = $request->re_order_level;
        $item->is_vat_item = $request->is_vat_item;
        $item->is_sscl_item = $request->is_sscl_item;
        $item->save();
        return response()->json(['message' => 'Item updated successfully'], 200);
    }
}
