<?php

namespace App\Models;

use App\Models\SubCategory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use DB;

class Category extends Model
{
    use HasFactory;
    protected $table = 'category'; 
    public $timestamps = false;

    public function categoryList()
    {
        return Category::all();
    }
    public function subcategoryList()
    {
        return DB::table('sub_categories')->get();
    }
    public function insertcategory($data,$categoryid="")
    {
        $obj = new Category();
        $obj->name = isset($data['name']) ? $data['name'] : "";
        $obj->created_at =date('Y-m-d H:i:s');
        $obj->save();
        $categoryid = $obj->id;
       
        return $categoryid;
    }
    public function updateCategory($data)
    {
        $obj = Category::find($data['id']);
        $obj->name = isset($data['name']) ? $data['name'] : "";
        $obj->updated_at =date('Y-m-d H:i:s');
        $obj->save();
        $categoryid = $obj->id;

        return $categoryid;
    }

    public function insertOrUpdatesubcategory($data)
    {
        $id = isset($data['id']) ? $data['id'] : null;
        $fk_category_id = isset($data['fk_category_id']) ? $data['fk_category_id'] : null;
        $name = isset($data['name']) ? $data['name'] : null;

        // Prepare data for update or create
        $subcategoryData = [
            'fk_category_id' => $fk_category_id,
            'name' => $name,
        ];

        // Use updateOrCreate to create or update the record
        $subcategory = SubCategory::updateOrCreate(['id' => $id], $subcategoryData);

        return $subcategory->id; // Return the ID of the created or updated record
    }
}
